android - 单击按钮时无法取消异步任务

标签 android android-asynctask

我正在尝试通过单击弹出框的按钮来取消/结束异步任务。但是,当我单击按钮时,不会调用 onCancelled() 方法。有人可以帮我解决这个问题吗?下面是我的代码:

public AuthenticationAsync(Context context, final String rid) {
    this.rid = rid;

    alertDialog = new AlertDialog.Builder(context).create();
    alertDialog.setTitle("Information");
    alertDialog.setMessage("RaspberryPi Validated");
    alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    cancel(true); //Cancelling async task on button click
                    dialog.dismiss();
                }
            });
}


@Override
protected Object doInBackground(Object[] params) {
    String metricData = String.valueOf(kuraPayload.getMetric("data"));
    if (metricData.isEmpty()) 
        subResponse = false;
}

@Override
protected void onCancelled() {
    Log.d("Async","cancelled");  //not being called
}

@Override
protected void onPostExecute(Object o) {
    if (subResponse) {
        asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.get(WSConstants.ADD_RPI_WS + MQTTFactory.getRaspberryPiById(), new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                Toast.makeText(ActivityContexts.getMainActivityContext(), "RaspberryPi Validated", Toast.LENGTH_LONG).show();
                alertDialog.show();
            }

    } 
}
}

最佳答案

看起来它永远不会进入 onCancelled(),因为您实际上是在 onPostExecute() 中调用 alertDialog.show()。因为 doInBackground() 已经完成,所以没有什么可以取消的。

cancel() 方法是在 doInBackground() 方法执行期间调用的,这是唯一在后台线程上运行的方法。

请注意,即使在doInBackground() 执行期间调用了cancel(),该方法的执行也不会立即停止。您应该定期检查 isCancelled(),如果它返回 true,则退出该方法。

doInBackground() 完成后,如果调用了 cancel(),则将调用 onCancelled() 而不是 onPostExecute().

这是一个基于您的代码的非常简单的测试:

public class AuthenticationAsync extends AsyncTask {

    AlertDialog alertDialog;
    String rid;

    public AuthenticationAsync(Context context, final String rid) {
        this.rid = rid;

        alertDialog = new AlertDialog.Builder(context).create();
        alertDialog.setTitle("Information");
        alertDialog.setMessage("RaspberryPi Validated");
        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        cancel(true); //Cancelling async task on button click
                        dialog.dismiss();
                    }
                });
    }

    @Override
    protected void onPreExecute(){
        //for testing, showing the dialog before the background Thread starts
        alertDialog.show();
    }

    @Override
    protected Object doInBackground(Object[] params) {
       //cycle forever until the user clicks OK
       while (true){
           try {
               Thread.sleep(1000);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
           //Check if user clicked OK in the dialog
           if (isCancelled()){
               //Exit the method if the user dismissed the dialog
               return null;
           }
       }
    }

    @Override
    protected void onCancelled() {
        Log.d("Async", "cancelled");  //this is called now
        Toast.makeText(MainActivity.this, "cancelled", Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onPostExecute(Object o) {
        Toast.makeText(MainActivity.this, "postExecute", Toast.LENGTH_LONG).show();
    }
}

结果:

在执行 doInBackground() 期间显示对话框:

dialog shown

点击确定后,调用onCancelled():

onCancelled

关于android - 单击按钮时无法取消异步任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30850246/

相关文章:

android - 如何将 ICE 候选人添加到 sdp 描述中

Android ACTION_SHUTDOWN 广播不工作

android - 如何每 30 分钟运行某种重复任务?

java - BroadcastReceiver 意外调用了 onReceive()

android - android中的图形表示

android - 我们如何键入 Sqlite 查询以创建具有属性的列的顺序真的很重要吗

android - 异步任务跟不上 for 循环 (firebase)

java - ProgressDialog Android AsyncTAsk

Android 等效于 ActionBarActivity 中的 getActivity()

java - 何时在 libgdx 中使用 Actor ?什么是缺点和优点?