Reputation: 603
I want to stop a Thread when the User leaves the Activity. It sounds so simple but no function, which i tried, works.
I start the Activity with the Code
lovi = new Intent(getApplicationContext(), listoverview.class);
lovi.putExtra("reloadAll", true);
startActivity(lovi);
In the onCreate of the listoverview i start the Thread with the Code
rlMF.start();
And rlMF looks like this:
public Thread rlMF = new Thread(new Runnable() {
public void run() {
reloadMissingFiles();
}
});
I tried in the onPause to use rlMF.stop(), .interrupt(), .suspend. Nothing stops it.
Upvotes: 1
Views: 6454
Reputation: 5798
You have to add some flag to to stop it. Stopping thread by other means might have dire consequences, like resource leaks.
For example:
volatile boolean activityStopped = false;
When creating runnable:
public Thread rlMF = new Thread(new Runnable() {
public void run() {
while (!activityStopped) {
// reloadMissingFiles() should check the flag in reality
reloadMissingFiles();
}
}
});
In onPause():
protected void onPause(){
super.onPause();
activityStopped = true;
}
Upvotes: 5
Reputation: 4341
Instead of Thread
try and use an AsyncTask
, this way you can call the cancel(boolean mayInterruptIfRunning)
method of the AsyncTask
. You should also keep in mind to catch the InteruptedException
that may be thrown if you use cancel(true)
.
Here's a usefull tutorial about Threads
, Handlers
and AsyncTask
that may help you.
Upvotes: 0
Reputation: 7892
Using the Android Handler
Runnable r = new Runnable()
{
public void run()
{
// do stuff
handler.post(this);
}
};
handler.post(r);
In the onPause:
protected void onPause(){
super.onPause();
handler.removeCallbacks();
}
Upvotes: 0