How to stop this thread in android?

≯℡__Kan透↙ 提交于 2019-11-29 05:22:46

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)

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.

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...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!