3

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

CosminO
  • 5,018
  • 6
  • 28
  • 50
naresh
  • 10,332
  • 25
  • 81
  • 124
  • You can check [this](http://stackoverflow.com/questions/680180/where-to-stop-destroy-threads-in-android-service-class) previously answered question, or you could paste some of your relevant code . – CosminO Apr 10 '12 at 13:46
  • A really good link!!! – dbm Apr 10 '12 at 14:20

3 Answers3

1

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();
}
Nishant Rajput
  • 2,053
  • 16
  • 28
1

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

dbm
  • 10,376
  • 6
  • 44
  • 56
0

//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`

}
Ravi1187342
  • 1,247
  • 7
  • 14