naresh
naresh

Reputation: 10392

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

Upvotes: 3

Views: 8593

Answers (3)

dbm
dbm

Reputation: 10485

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

Upvotes: 1

Ravi1187342
Ravi1187342

Reputation: 1277

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

}

Upvotes: 0

Nishant Rajput
Nishant Rajput

Reputation: 2063

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();
}

Upvotes: 1

Related Questions