取消时,AsyncTask不取消(布尔值)

时间:2016-02-03 14:31:34

标签: java android android-asynctask

我有一些问题取消了AsyncTask。我对Android编程很新,所以我可能在某处犯了错字。

按下取消按钮后会发生以下情况:

  • 在cancelButton的onClick事件中调用cancel(true)似乎修改了isCancelled()使用的变量,因此for-loopin doInBackground将被break语句终止。但是:
  • onCancelled(String)未被调用。

如果我不按取消,我会得到预期的行为,所以问题只涉及onCancelled方法。

代码如下:

public class CustomAsyncTask extends AsyncTask<String, Integer, String> {
//Variables to be used by onPreExecute, onPostExecute, onProgressUpdate
//and onCancelled, as they can operate on the UI thread.
private ProgressBar progressBar;
private Button submitButton;
private Button cancelButton;
private TextView resultText;
private int max;

//Constructor initializing the field variables.

@Override
protected void onPreExecute() {
    progressBar.setProgress(0);
    progressBar.setVisibility(View.VISIBLE);
    submitButton.setVisibility(View.INVISIBLE);
    cancelButton.setVisibility(View.VISIBLE);
    resultText.setBackgroundResource(R.color.white);
    resultText.setText("Working on item 1 of " + max);
    cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            cancel(true);
        }
    });
}

@Override
protected String doInBackground(String ... strings) {

    for(int count = 0; count < strings.length; ++count) {
        if(isCancelled()) {
            break;
        }
        try {
            Thread.sleep(1000);
            publishProgress(count);
        } catch(Exception e) {
            throw new Error(e);
        }
    }

    return "Task completed: " + strings[0];
}

@Override
protected void onPostExecute(String result) {
    progressBar.setVisibility(View.INVISIBLE);
    submitButton.setVisibility(View.VISIBLE);
    cancelButton.setVisibility(View.INVISIBLE);
    resultText.setText(result);
}

@Override
protected void onProgressUpdate(Integer ... values) {
    progressBar.setProgress(values[0]);
    //don't mind the line under, some testing...
    resultText.setText("Working on item " + (values[0]+2) + " of " + max);
}

@Override
protected void onCancelled(String result) {
    progressBar.setVisibility(View.INVISIBLE);
    submitButton.setVisibility(View.VISIBLE);
    cancelButton.setVisibility(View.INVISIBLE);
    resultText.setBackgroundResource(R.color.red);
    resultText.setText("Canceled.");
}
}

有没有人知道为什么没有调用onCancelled(String)?我一直在StackOwerFlow上寻找类似的问题,但是没有找到任何能解决我问题的问题: - )

AsyncTask由以下Activity启动(在按下asyncTaskSubmit按钮时):

public class AsyncTaskActivity extends AppCompatActivity {

    private EditText editText;
    private Button asyncTaskSubmit;
    private Button asyncTaskCancel;
    private ProgressBar progressBar;
    private TextView textView;
    private static final int MAX = 10;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //call super, initialize fieldvariables with findViewById.
        asyncTaskSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = editText.getText().toString();
                String [] doJobs = new String[MAX];
                //dummydata
                for(int x = 0; x < doJobs.length; x++) {
                    doJobs[x] = text;
                }
                new CustomAsyncTask(
                    progressBar,
                    asyncTaskSubmit,
                    asyncTaskCancel,
                    textView,
                    MAX
                ).execute(doJobs);      
            }
        });
    }
}

其他信息:

  • SDK(分钟):16
  • SDK(目标):23
  • 仿真器设备:Google nexus 5(API 23)

提前致谢!

-Superdids

1 个答案:

答案 0 :(得分:0)

微小的修改似乎提供了预期的结果。我将cancel(boolean)的参数从true更改为false:

cancelButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //cancel(true);
        cancel(false);
    }
});

由于参数(boolean mayInterruptIfRunning)声明:

  • 如果执行此任务的线程应该被中断,则为真;否则,允许完成正在进行的任务。

至少在我的实现中,这意味着如果我在cancel(..)中传递true作为参数,则doInBackground方法将不会返回。