[英]Android pause/resume AsynTask
I have a UI thread(MainActivity) calling an AsynTask object(DownloadManager), which, in turn calls 3 threads (DownloaderThread). 我有一个UI线程(MainActivity)调用一个AsynTask对象(DownloadManager),该对象又调用了3个线程(DownloaderThread)。
How do I pause/resume the 3 DownloaderThreads without pausing the AsynTask or the UI thread? 如何在不暂停AsynTask或UI线程的情况下暂停/恢复3个DownloaderThreads?
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): 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: DownloaderThread(实现Runnable,并传递给DownloadManager中的Thread实例:
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. 一旦启动AsyncTask,您就无法真正暂停它。 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 . 但是我建议为您的方案完成任务的最佳方法是使用Service 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.