代码如下:

/* * 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 booleancancel(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 whencancelis called, this task should never run. If the task has already started, then themayInterruptIfRunningparameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.

Calling this method will result inonCancelled(Object)being invoked on the UI thread afterdoInBackground(Object[])returns. Calling this method guarantees thatonPostExecute(Object)is never invoked. After invoking this method, you should check the value returned byisCancelled()periodically fromdoInBackground(Object[])to finish the task as early as possible.

Parameters
mayInterruptIfRunning trueif the thread executing this task should be interrupted; otherwise, in-progress tasks are allowed to complete.
Returns
  • falseif the task could not be cancelled, typically because it has already completed normally;trueotherwise
See Also
  • isCancelled()
  • onCancelled(Object)



更多相关文章

  1. Android中的一些方法-----生生不息
  2. Android(安卓)获取屏幕分辨率
  3. Android(安卓)Timer 实现方法
  4. Failed to install the following Android(安卓)SDK packages as
  5. 在android里保存数据的三种形式(Saving Data)
  6. Android(安卓)显示/隐藏 软键盘 方法
  7. Android(安卓)属性动画详解
  8. 浅谈Java中Collections.sort对List排序的两种方法
  9. Python list sort方法的具体使用

随机推荐

  1. android sp wp
  2. WebView加载网页基本配置
  3. Android(安卓)Activity启动机制流程和四
  4. Android(安卓)学习 之 键盘问题
  5. Android(安卓)如何更改包名
  6. 关注 在自我和潮流中一直前进的榜样 !
  7. 反向控制-Inversion of Control(JAVA App
  8. Jenkins+Gradle实现Android移动端自动打
  9. Android(安卓)SeekBar显示进度在thumb上
  10. Android仿微信聊天语言点击喇叭动画效果