【发布时间】:2016-05-26 21:54:53
【问题描述】:
我有一个位于服务内部的处理程序,我阻塞了这个线程,直到用户选择停止服务。为了减少 CPU 密集度,我尝试使用 Thread.sleep() 并在间隔 10 minutes 后重复检查阻塞条件。这是我的handlemessage 的实现:
@Override
public void handleMessage(Message msg) {
Log.e("Service", "looper started");
GPSThread gp=new GPSThread(getApplicationContext());
gp.start();
ModeController mc=new ModeController(getApplicationContext());
mc.start();
NetworkSniffer nh=new NetworkSniffer(getApplicationContext());
nh.start();
while(stopService) //stopService is a volatile boolean i use to block until user opts to stop the service
{
try {
Thread.sleep(10*60*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mc.stopThread();
gp.stopThread();
nh.stopNetworkThread();
stopSelf(msg.arg1);
}
现在我的问题是,如果我将 stopService 的值更改为 false(通过公共函数),可能需要 10 分钟才能退出 while 循环。如果它是一个线程,我会使用 Thread.interrupt() 并退出 while 循环。
所以我的问题是如何为 Handler 实现类似的事情,即如何在 Handler 中为 Thread.sleep() 抛出 InterruptedException。
【问题讨论】:
标签: java android multithreading thread-sleep android-handler