Skip to content Skip to sidebar Skip to footer

Start Handler Thread And Finish The Activity

If we start a handler thread / thread in an activity and then the activity is destroyed when we press back button, What happens to the handler thread? Is it still in running state?

Solution 1:

Simply , your Thread is in running state.

It is actually bad practice to keep a thread running after onPause. The reason is that after onPause your application may drop out of memory at any time without your being able to know, therefore you will not be able to clean up after yourself.

The proper way to do it is stopping the thread onPause and recreating it onResume. If you need state you can use Android's built in saveState methods or settings or whichever to keep that.

Your related thread is here and here

Solution 2:

The thread won't be destroyed until its job is finished. So make sure all its job is finished before closing an activity. Because the thread may contain any reference of views and it may try to access it after the job is done. HandlerThread can be stopped by calling

thread.quitSafely();

this ensures that all pending messages are processed before the thread stops.

Post a Comment for "Start Handler Thread And Finish The Activity"