理想的方式取消正在执行的AsyncTask理想、方式、AsyncTask

2023-09-11 10:49:12 作者:你把我弄丢了

我远程在后台线程中使用运行音频文件取和音频文件播放操作的AsyncTask 。 A 撤销进度条显示的提取操作运行的时间。

I am running remote audio-file-fetching and audio file playback operations in a background thread using AsyncTask. A Cancellable progress bar is shown for the time the fetch operation runs.

我要当用户取消取消/放弃的AsyncTask 运行(决定反对)的操作。什么是理想的方式来处理这种情况?

I want to cancel/abort the AsyncTask run when the user cancels (decides against) the operation. What is the ideal way to handle such a case?

推荐答案

刚刚发现, AlertDialogs 布尔取消(...); 我一直在使用无处不在实际上已经什么都不做。伟大的。照片 所以......

Just discovered that AlertDialogs's boolean cancel(...); I've been using everywhere actually does nothing. Great. So...

public class MyTask extends AsyncTask<Void, Void, Void> {

    private volatile boolean running = true;
    private final ProgressDialog progressDialog;

    public MyTask(Context ctx) {
        progressDialog = gimmeOne(ctx);

        progressDialog.setCancelable(true);
        progressDialog.setOnCancelListener(new OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                // actually could set running = false; right here, but I'll
                // stick to contract.
                cancel(true);
            }
        });

    }

    @Override
    protected void onPreExecute() {
        progressDialog.show();
    }

    @Override
    protected void onCancelled() {
        running = false;
    }

    @Override
    protected Void doInBackground(Void... params) {

        while (running) {
            // does the hard work
        }
        return null;
    }

    // ...

}