How to safely exit HandlerThread looper

I have a HandlerThread to which I continue to publish runnable every 5 seconds. Something like that:

HandlerThread thread = new HandlerThread("MyThread"); thread.start(); Handler handler = new Handler(thread.getLooper()); handler.post(new Runnable() { public void run() { //... handler.postDelayed(this, 5000); } }); 

I need to get out of the looper at some point, after 60 seconds or something like that. Therefore, I write:

 mainHandler = new Handler(Looper.myLooper()); //main thread's mainHandler.postDelayed(new Runnable() { @Override public void run() { thread.getLooper().quit(); } }, 60000); 

I think this causes the looper to abruptly stop working, so I start to receive “warning” messages:

W / MessageQueue (3726): java.lang.RuntimeException: Handler (android.os.Handler) {4823dbf8} sends a message to the dead thread handler

I want to avoid this msg error, I thought I could solve it using the Looper.quitSafely() method .. but I checked the API and it is no longer available. Does anyone know what happened to him? (It is not outdated, like some other methods).

Is there a way so that I can safely leave the looper? Thanks!

+7
android looper handlers
source share
2 answers

You can try to use a boolean to find out if the code should run. Something like that:

 private boolean runHandler = true; ... HandlerThread thread = new HandlerThread("MyThread"); thread.start(); Handler handler = new Handler(thread.getLooper()); handler.post(new Runnable() { public void run() { if(runHandler){ //... handler.postDelayed(this, 5000); } } }); mainHandler = new Handler(Looper.myLooper()); //main thread's mainHandler.postDelayed(new Runnable() { @Override public void run() { runHandler = false; } }, 60000); 
+1
source share

Im not Thread Guru, but this method can give you direction:

  ... _thread.setRunning(true); _thread.start(); .. public void stopThread(){ boolean retry = true; _thread.setRunning(false); while (retry) { try { _thread.join(); retry = false; Log.e("test", "thread stopped"); } catch (InterruptedException e) { Log.e("test", "can't stop thread, retrying..."); // we will try it again and again... } } } 

In your topic:

 while (isRunning) { //... } 

1 all of you implement the run method in a loop ( while(isRunnig){} ).

At the end, you switch the flag to false and "wait" to join .

0
source share

All Articles