Skip to content Skip to sidebar Skip to footer

How To Stop This Thread In Android?

In my application i am using this thread to rotate the Second hand on the clock. But the Problem is while i close the activity, the thread is still remain run. I want to stop the t

Solution 1:

try this code in your activity -

@Override
protected void onDestroy() {
    android.os.Process.killProcess(android.os.Process.myPid());
}

When you exit from your application, your application process is not actually destroyed. If you destroy your process, all child processes(all your child threads) will be destroyed.


Solution 2:

Ok, that means you want to create a service that will have been running in background. One thing is that service is one type of thread, if it will run in background that will drain your device battery power. So, if you kill your process then the thread as well as your service will destroy. So, stop your thread like -

boolean running = true;

public void run() {
   while(running) {
       // your working code...
   }
}

@Override
protected void onDestroy() {
    running = false;
}

When you exit your app, the thread will stop. And the other will stay running, that is your service. Don't try to stop your thread forcefully, or suspend. It is deprecated, if your while loop of the thread breaks, then it will automatically destroy your thread according to JVM rules. Hope it will help you. Have fun...


Solution 3:

don't myThread.join() on the UI thread since it will block until the Thread finished and your App might ANR. Also Thread.currentThread().interrupt(); will try to interrupt the UI thread which is really bad.

You can put MyThread.interrupt() in onDestroy, onPause or onStop (+ recreate the Thread in the corresponding start callback)


Post a Comment for "How To Stop This Thread In Android?"