简体   繁体   中英

Android pause/resume AsynTask

I have a UI thread(MainActivity) calling an AsynTask object(DownloadManager), which, in turn calls 3 threads (DownloaderThread).

How do I pause/resume the 3 DownloaderThreads without pausing the AsynTask or the UI thread?

Following is the code I have currently implemented for the pause functionality, but when the Pause button is clicked, the app crashes with the dialog: "app has stopped". Code:

DownloadManager (AsynTask):

public void onPause() {
    try{
        t0.wait();
        t1.wait();
        t2.wait();
        this.wait();
    }catch (InterruptedException ex){

    }
}

DownloaderThread (implements Runnable and is passed to a Thread instance in DownloadManager:

public class DownloaderThread implements Runnable {
    private Object mPauseLock;
    private Boolean mPaused;
    private Boolean mFinished;
public void run(){
    android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
    try{
        while(!mFinished){
            //do something
            synchronized (mPauseLock){
                while (mPaused){
                    try{
                        mPauseLock.wait();
                    }catch (InterruptedException e){

                    }
                }
            }
        }
    }
}

public void onPause(){
    synchronized (mPauseLock){
        mPaused = true;
    }
}

You can't really pause an AsyncTask once it started. You can, however, store the progress when activity is paused/destroyed and start from the progress once you are back to the original Activity. But I recommend the best way to complete task for your scenario is to use Service .

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