0

I can't stop this thread when I exit my activity or application.

public class MyThread extends Thread {
        public Handler handler;
        @Override
        public void  try{
                Looper.prepare();
                handler = new Handler();
                Looper.loop();
        }
    }
    ...

myThread = new MyThread();
myThread.start();

final Runnable runnable = new Runnable() {
       @Override
       public void run(){
             doSomething();
             myThread.handler.postDelayed(this,30*1000);
       }
};
myThread.handler.post(runnable);

@Override
public void onStop(){    
       myThread.handler.removeCallbacksAndMessages(null);
       myThread.handler.getLooper().quit();   
       myThread = null;          
}

I can confirm that all the onStop() code is run, but the logcat still shows the thread running after I exit the application.

I think even if I remove the battery and smash the device with a sledgehammer it will still keep running, I've tried everything. :~) I must be missing something about handlers, loopers, and threads. Please help.

aez
  • 2,406
  • 2
  • 26
  • 46

1 Answers1

1

add a boolean flag in the Activity, say "shouldThreadRun", set to true in onResume(), set to false in onPause()

In run() of the Thread, check whether the Activity is still running

if(shouldThreadRun){
    doSomething();
    myThread.handler.postDelayed(this,30*1000);
}
Patrick Chan
  • 1,019
  • 10
  • 14
  • Thanks Patrick. I'm not sure how this is possible, but even when I set shouldThreadRun=false in my onPause(), it still continues to run, and I set a breakpoint in the run() of the thread, and I see that somehow shouldThreadRun has been reset to true, and I don't know how that's possible. I even have it declared as volatile. – aez Dec 06 '14 at 18:34
  • I would also ask, then what is the use of looper.quit()? or removeCallbacksAndMessages()? – aez Dec 06 '14 at 18:47
  • Try to prevent using Looper and Handler, use AsyncTask for background task and UI interaction instead. I guarantee the async task could be stopped by the flag. – Patrick Chan Dec 07 '14 at 03:24