aez
aez

Reputation: 2396

Can't stop android thread

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.

Upvotes: 0

Views: 228

Answers (1)

Patrick Chan
Patrick Chan

Reputation: 1029

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);
}

Upvotes: 1

Related Questions