如何循环服务? [英] How to loop a service?
问题描述
我的服务,需要检查的东西,每分钟和
My service needs to check for something every minute and
while(true)
{
Thread.sleep(60000)
//REST OF CODE HERE//
}
不工作。提出申请冻结,并要求我强行制止。
is not working. Making the application freeze and asking me to forcefully stop it.
我相信这个问题是与while循环,但我认为这是无限重复的服务每当ONSTART()方法执行的唯一途径。
I am sure the problem is with the while loop but I thought it was the only way to infinitely repeat the service whenever the onStart() method executes.
任何建议都是AP preciated。
Any suggestions are appreciated.
修改
我固定它,如果你想知道如何code看起来好你去:
I fixed it and in case you were wondering how the code looks like well there you go:
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Toast.makeText(this, "Service running", Toast.LENGTH_SHORT).show();
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
Toast.makeText(protectionService.this, "5 secs has passed", Toast.LENGTH_SHORT).show();
}
};
new Thread(new Runnable(){
public void run() {
// TODO Auto-generated method stub
while(true)
{
try {
Thread.sleep(5000);
handler.sendEmptyMessage(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
基本上该服务被称为和服务的任务将反复每5秒在这种情况下。
Basically the service is been called and the tasks of that service will be repeated every 5 secs in that case.
我要感谢vineetska,雅努什和inazaruk的建议使用处理程序。我要感谢大家谁回答还有,你的帮助是非常AP preciated。
I would like to thank vineetska, Janusz and inazaruk for suggesting to use Handlers. I would like to thank everyone who answered as well, your help was very much appreciated.
推荐答案
创建你的服务线程,并把while循环有这样的:
create a thread in your service and put while loop there like this:
new Thread(new Runnable(){
public void run() {
// TODO Auto-generated method stub
while(true)
{
Thread.sleep(60000)
//REST OF CODE HERE//
}
}
}).start();
这篇关于如何循环服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!