Sourav Kanta Sourav Kanta - 11 months ago 36
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

public void handleMessage(Message msg) {
Log.e("Service", "looper started");
GPSThread gp=new GPSThread(getApplicationContext());
ModeController mc=new ModeController(getApplicationContext());
NetworkSniffer nh=new NetworkSniffer(getApplicationContext());
while(stopService) //stopService is a volatile boolean i use to block until user opts to stop the service
try {
} catch (InterruptedException e) {
// TODO Auto-generated catch block

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.


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.


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: