Android AsyncTask 异步任务取消

时间:2021-08-29 05:18:32

代码如下:

/*
* Copyright (c) 2015. 版权归5hand所有
*/

package com.example.dell.myapplication;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.os.AsyncTask;

public class MainActivity extends ActionBarActivity {

private static String TAG = "MainActivity";
private Task task;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
task = new Task();
Button startButton = (Button) findViewById(R.id.start);
startButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
task.execute();
}
});

Button stopButton = (Button) findViewById(R.id.stop);
stopButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
boolean flag = task.cancel(true);
String str;
if (flag) {
str = "取消成功";
}
else {
str = "取消失败";
}
Toast.makeText(MainActivity.this, str , Toast.LENGTH_LONG).show();
}
});
}

class Task extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... str) {
int i = 0;
Log.e(TAG, "开始了, i:" + i);
try {
Thread.sleep(5000);
i = 10;
} catch (InterruptedException e) {
e.printStackTrace();
}

return String.valueOf(i);
}

@Override
protected void onPostExecute(String result) {
Log.e(TAG, "完成了, i:" + result);
}

@Override
protected void onCancelled (String result) {
Log.e(TAG, "取消了, i:" + result);
}
}
}

这里主要用到了 AsyncTask类的cancle() 方法

要想中断任务 调用cancle()方法时要传递boolean参数为true ,

并且中断成功之后返回true, 并且执行onCancelled()方法,

onPostExceute()方法将不在执行,否则返回false


关于此方法的说明如下:

public final boolean cancel (boolean mayInterruptIfRunning)

Added in API level 3

Attempts to cancel execution of this task. This attempt will fail if the task has already completed, already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.

Calling this method will result in onCancelled(Object) being invoked on the UI thread after doInBackground(Object[]) returns. Calling this method guarantees thatonPostExecute(Object) is never invoked. After invoking this method, you should check the value returned by isCancelled() periodically from doInBackground(Object[]) to finish the task as early as possible.

Parameters
mayInterruptIfRunning true if the thread executing this task should be interrupted; otherwise, in-progress tasks are allowed to complete.
Returns
  • false if the task could not be cancelled, typically because it has already completed normally; true otherwise
See Also