Stop Thread onPause

2019-01-29 04:30发布

问题:

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.

回答1:

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


回答2:

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


回答3:

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.