0

我试图在 AsyncTask 的“doInBackGround”方法运行时从主线程取消一个对话框。当我下载照片时,会弹出一个进度对话框,下载完成后,我在 onPostExecute 中关闭()对话框。如果连接速度很慢,对话框会持续一段时间,我无法取消它,直到出现超时错误或完成下载。如何使用后退按钮以便主线程可以访问。这是我的代码的样子:

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {


    protected void onPreExecute() {
        //this piece code doesn't seem to work
        progressDialog = ProgressDialog.show(context, "",
                "Image loading", true);
    }

    protected Bitmap doInBackground(String... urls) {
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        //bmImage.setImageBitmap(result);
        progressDialog.dismiss();
        someMethod(result);

    }
}
4

3 回答 3

1

您可以拦截事件,并使用方法onBackKeyPressed取消任务。cancel

请参阅该链接: 取消正在执行的 AsyncTask 的理想方法

于 2013-03-12T16:18:06.503 回答
1

使用可取消的进度对话框,将取消侦听器传递给进度对话框并取消该方法中的任务,例如

protected void onPreExecute() {
    progressDialog = ProgressDialog.show(activity, "Searching files", "Scanning...", true, true,
            new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    // When dialog in cancelled, need to explicitly cancel task otherwise it keeps on running
                    cancel(true);
                }
            }
    );

    progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
}
于 2013-03-12T16:28:12.693 回答
0

您可以尝试使用 a ProgressDialogwhich is cancelable。这是该方法的签名:-

public static ProgressDialog show (Context context, CharSequence title, CharSequence message, boolean indeterminate, boolean cancelable)
于 2013-03-12T16:20:05.833 回答