Android AsyncTask 异步任务取消

代码如下:

/*
 * 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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值