Android笔记(三十七) 如何停止AsyncTask

  当我们加载一张图片的时候,加载的过程中我们想要取消操作,该怎么办呢?调用Asynctask的 cancel) 方法就可以了,我们看代码:

  先看一个例子:

  MainAciticty.java

package cn.lixyz.asynctest;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends Activity {

    private Button btStart;
    private Button btStop;
    private ImageView imageView;
    private ProgressBar progressBar;
    private String URL = "http://ww3.sinaimg.cn/bmiddle/612c96afjw1ewwftl3uqkj20u00koq48.jpg";

    @Override
    protected void onCreateBundle savedInstanceState) {
        super.onCreatesavedInstanceState);

        setContentViewR.layout.activity_main);

        //获取组件
        btStart = Button) findViewByIdR.id.btStart);
        btStop = Button) findViewByIdR.id.btStop);
        imageView = ImageView) findViewByIdR.id.imageView);
        progressBar = ProgressBar) findViewByIdR.id.progressBar);

        //给button设置点击事件,点击按钮,启动异步任务
        MyOnClickListener moc = new MyOnClickListener);
        btStart.setOnClickListenermoc);
        btStop.setOnClickListenermoc);
    }

    class MyOnClickListener implements View.OnClickListener {

        LoadImage li = new LoadImage);
        @Override
        public void onClickView v) {
            switch v.getId)){
                case R.id.btStart:
                    li.executeURL);
                    break;
                case R.id.btStop:
                    li.canceltrue);
                    break;
            }
        }
    }

    class LoadImage extends AsyncTask<String, Integer, Bitmap> {


        //开始执行耗时操作,连接网络获取图片,并且将Bitmap返回
        @Override
        protected Bitmap doInBackgroundString... params) {

            int i = 0;
            while true) {
                if i > 100) {
                    break;
                }
                i++;
                try {
                    Thread.sleep100);
                } catch InterruptedException e) {
                    e.printStackTrace);
                }
                Log.d"TTTT","" + i);
                publishProgressi);
            }


            String url = params[0];
            Bitmap bitmap = null;
            URLConnection connection;
            InputStream is;
            try {
                connection = new URLurl).openConnection);
                is = connection.getInputStream);
                BufferedInputStream bis = new BufferedInputStreamis);
                bitmap = BitmapFactory.decodeStreambis);
                is.close);
                bis.close);
            } catch IOException e) {
                e.printStackTrace);
            }
            return bitmap;
        }

        //onPreExcute方法是在doInBackGround方法前执行,用于做一些初始化操作,这里将progressBar显示出来
        @Override
        protected void onPreExecute) {
            super.onPreExecute);
            progressBar.setVisibilityView.VISIBLE);
        }


        //doInBackGround方法执行后,会自动执行该方法,获取到doInBackGround返回的对象,然后更改UI
        @Override
        protected void onPostExecuteBitmap bitmap) {
            super.onPostExecutebitmap);
            progressBar.setVisibilityView.GONE);
            imageView.setImageBitmapbitmap);
        }

        @Override
        protected void onProgressUpdateInteger... values) {
            super.onProgressUpdatevalues);
            progressBar.setProgressvalues[0]);
        }
    }
}

  acticity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="4">
        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"/>
        <ProgressBar
            android:id="@+id/progressBar"
            android:visibility="gone"
            android:layout_centerInParent="true"
            style="@style/Widget.AppCompat.ProgressBar.Horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </RelativeLayout>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1">
        <Button
            android:id="@+id/btStart"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_gravity="center"
            android:text="点击载入" />
        <Button
            android:id="@+id/btStop"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="点击退出"/>

    </LinearLayout>
</LinearLayout>

  执行结果:

  点击退出按钮之后,进度条停止加载了,似乎已经成功了,但是我们看log:

  后台进度依旧在更新着,AsyncTask实际上并没有停止,原来,调用了cancel之后,并不是真正的退出,而是将AsyncTask标记为Canceled,你需要在doInBackground中随时查看状态,如果是canceled,就退出:

package cn.lixyz.asynctest;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends Activity {

    private Button btStart;
    private Button btStop;
    private ImageView imageView;
    private ProgressBar progressBar;
    private String URL = "http://ww3.sinaimg.cn/bmiddle/612c96afjw1ewwftl3uqkj20u00koq48.jpg";

    @Override
    protected void onCreateBundle savedInstanceState) {
        super.onCreatesavedInstanceState);

        setContentViewR.layout.activity_main);

        //获取组件
        btStart = Button) findViewByIdR.id.btStart);
        btStop = Button) findViewByIdR.id.btStop);
        imageView = ImageView) findViewByIdR.id.imageView);
        progressBar = ProgressBar) findViewByIdR.id.progressBar);

        //给button设置点击事件,点击按钮,启动异步任务
        MyOnClickListener moc = new MyOnClickListener);
        btStart.setOnClickListenermoc);
        btStop.setOnClickListenermoc);
    }

    class MyOnClickListener implements View.OnClickListener {

        LoadImage li = new LoadImage);
        @Override
        public void onClickView v) {
            switch v.getId)){
                case R.id.btStart:
                    li.executeURL);
                    break;
                case R.id.btStop:
                    li.canceltrue);
                    break;
            }
        }
    }

    class LoadImage extends AsyncTask<String, Integer, Bitmap> {


        //开始执行耗时操作,连接网络获取图片,并且将Bitmap返回
        @Override
        protected Bitmap doInBackgroundString... params) {

            int i = 0;
            while true) {
                if i > 100) {
                    break;
                }
                if isCancelled)){
                    break;
                }
                i++;
                try {
                    Thread.sleep100);
                } catch InterruptedException e) {
                    e.printStackTrace);
                }
                Log.d"TTTT","" + i);
                publishProgressi);
            }


            String url = params[0];
            Bitmap bitmap = null;
            URLConnection connection;
            InputStream is;
            try {
                connection = new URLurl).openConnection);
                is = connection.getInputStream);
                BufferedInputStream bis = new BufferedInputStreamis);
                bitmap = BitmapFactory.decodeStreambis);
                is.close);
                bis.close);
            } catch IOException e) {
                e.printStackTrace);
            }
            return bitmap;
        }

        //onPreExcute方法是在doInBackGround方法前执行,用于做一些初始化操作,这里将progressBar显示出来
        @Override
        protected void onPreExecute) {
            super.onPreExecute);
            progressBar.setVisibilityView.VISIBLE);
        }


        //doInBackGround方法执行后,会自动执行该方法,获取到doInBackGround返回的对象,然后更改UI
        @Override
        protected void onPostExecuteBitmap bitmap) {
            super.onPostExecutebitmap);
            progressBar.setVisibilityView.GONE);
            imageView.setImageBitmapbitmap);
        }

        @Override
        protected void onProgressUpdateInteger... values) {
            super.onProgressUpdatevalues);
            progressBar.setProgressvalues[0]);
        }
    }
}
cancel

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注