Sourav Kanta Sourav Kanta - 6 months ago 11
Android Question

How do I send an interrupt to a handler to break a Thread.sleep()?

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.

Answer

If it were a thread I would have used a Thread.interrupt() and quit the while loop.

Actually, the code >>is<< running on a thread, so you if you could work out what that thread is, you could interrupt it.

Putting that aside, the way that you should do this is to have the code where you would have tried to interrupt the thread call Service.stopService.

References:

This approach works when the thread that is sleeping is the service's handler thread. If you have explicitly created the thread yourself, then you will need to keep track of the thread our created and use Thread.interrupt on it. (And you could use the Thread.interrupted state rather than a custom stopService flag.)

However, a better idea would be to avoid the sleep loop: http://stackoverflow.com/a/845291/139985