简体   繁体   中英

android - How to stop the running thread safely

My application has two activities. Activity one(A1) starts the thread. Let's suppose this activity(A1) goes to pause-state. I want to stop the running thread safely; how to do this?

thanks

you can use return statement in your Threads run method like this...

public void run(){

    if(isDone)
    {     
      return;
    }

}

or you can use this...

if(thread != null)
{
    Thread t1 = thread;
    thread = null;
    t1.interrupt();
}

I would suggest you having a look at the AsyncTask and IntentService .

//use boolean flag in side run method of Thread as following

boolean isActivityPaused = false;

       public void run(){

    // use isActivityPaused boolean flag here to stop your Thread

        while(!isActivityPaused){ 



        }

        }

now this is onPause() methed of your Activity

public void onPause(){

isActivityPaused = true; // set isActivityPaused= true to stop your `Thread`

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM