I have a Handler that is inside a Service and I block this thread until the user chooses to stop the service. To make it less CPU intensive I am trying to use Thread.sleep() and repeat checking the blocking condition after an interval of 10 minutes
. Here's my implementation of my 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);
}
Now my problem is that if I change the value of stopService to false (through a public function) it might take upto 10 minutes to quit the while loop. If it were a thread I would have used a Thread.interrupt() and quit the while loop.
So my question is how do I achieve a similar thing for Handler i.e, how to throw a InterruptedException for Thread.sleep() inside a Handler.