代码如下:

/* * 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 {        @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
  • isCancelled()
  • onCancelled(Object)



更多相关文章

  1. Android(安卓)transformClassesWithDexForAdh5Debug 的解决方法
  2. Android(安卓)Jetpack Components of ViewModel 学习笔记
  3. 一个简单的例子让你彻底了解android 中Activity的生命周期
  4. android 拦截鼠标按键
  5. android .9 图片的全能适配方法
  6. Android(安卓)计算控件尺寸
  7. android WiFi 开关代码
  8. 浅谈Java中Collections.sort对List排序的两种方法
  9. Python list sort方法的具体使用

随机推荐

  1. Android实现KSOAP2访问WebService
  2. Android 如何 画 柱状图 -------自定义Vi
  3. reason: HttpHostConnect Connection to
  4. android 切换到阿拉伯语电话号码+号显示
  5. android 添加音乐作为铃声
  6. Android下MP3播放器的实现源代码02
  7. android用ImageView显示网络图片
  8. Android Audio代码分析21 - 创建AudioEff
  9. Android(安卓)Audio代码分析15 - testPla
  10. Android的string.xml文件中的特殊字符显