简体   繁体   English

关于线程的问题在Android中使用AsyncTask停止或不在progressDialog中

[英]Issues about thread stopped or not in progressDialog in Android with AsyncTask

I have a code as following, and the thing is every time I cancel the dialog, InterruptException occurs and the cancel method doesn't really work. 我有一个代码如下,每当我取消对话框时,就会发生InterruptException并且cancel方法不起作用。 As I shows below, I print the state of cancel in the onPostExecute method, it is a false instead of true. 如下所示,我在onPostExecute方法中打印cancel状态,它是false而不是true。 Before adding isRunning parameter, obviously the thread was still running in the background. 在添加isRunning参数之前,显然线程仍然在后台运行。 Although isRunning does stop the thread( the onPostExecute method was executed), I want to know why the exception happened and why I still got a false in the isCanceled method. 虽然isRunning确实停止了线程(执行了onPostExecute方法),但我想知道为什么异常发生以及为什么我仍然在isCanceled方法中出现false Thanks! 谢谢!

public void startDownload(View view){
    dialog = new ProgressDialog(this);
    final Downloader downloader = new Downloader(this, dialog);
    downloader.execute(0);
    dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            downloader.cancel(true);
        }
    });
}


public class Downloader extends AsyncTask<Integer, Integer, String> {
private Context context;
private PowerManager.WakeLock wakeLock;
private ProgressDialog dialog;
public boolean isRunning = true;

public Downloader(Context context, ProgressDialog dialog) {
    this.context = context;
    this.dialog = dialog;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
            getClass().getName());
    wakeLock.acquire();

    dialog.setMessage("Downloading...");
    dialog.setIndeterminate(true);
    dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    dialog.setCancelable(false);
    dialog.setButton(ProgressDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            isRunning = false;
        }
    });
    dialog.show();
}

@Override
protected String doInBackground(Integer[] params) {
    int count = params[0];
    while(count<100 && isRunning){
        publishProgress(count);
        try{
            count++;
            System.out.println(count);
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    return null;
}

@Override
protected void onProgressUpdate(Integer... values) {
    super.onProgressUpdate(values);
    dialog.setIndeterminate(false);
    dialog.setMax(100);
    dialog.setProgress(values[0]);
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    wakeLock.release();
    dialog.dismiss();
    if (s != null)
        Toast.makeText(context,"Download error: "+ s, Toast.LENGTH_LONG).show();
    else
        Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
    System.out.println(isCancelled());
}

} }

Make sure you're not executing another AsyncTask, or start this one in parallel, using .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) instead of .execute() . 确保您没有执行另一个AsyncTask,或使用.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)而不是.execute()并行启动它。 Otherwise, if you're already running another AsyncTask in background this other one will not run until that last one finishes. 否则,如果您已经在后台运行另一个AsyncTask,那么另一个AsyncTask将在最后一个完成之前运行。

On the other hand, try not to track AsyncTask lifecycle status with a custom boolean, to do so, use isCancelled() to check stuff at runtime or break any loop and if required, override the AsyncTask's onCancelled() method to implement any functionality you may need at that point. 另一方面,尽量不要使用自定义布尔值跟踪AsyncTask生命周期状态,为此,使用isCancelled()在运行时检查内容或中断任何循环,如果需要,覆盖AsyncTask的onCancelled()方法以实现任何功能可能需要那个点。

Don't forget to check the reference: AsyncTask - Android Developers . 别忘了检查参考: AsyncTask - Android Developers

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM