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 onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //获取组件 btStart = (Button) findViewById(R.id.btStart); btStop = (Button) findViewById(R.id.btStop); imageView = (ImageView) findViewById(R.id.imageView); progressBar = (ProgressBar) findViewById(R.id.progressBar); //给button设置点击事件,点击按钮,启动异步任务 MyOnClickListener moc = new MyOnClickListener(); btStart.setOnClickListener(moc); btStop.setOnClickListener(moc); } class MyOnClickListener implements View.OnClickListener { LoadImage li = new LoadImage(); @Override public void onClick(View v) { switch (v.getId()){ case R.id.btStart: li.execute(URL); break; case R.id.btStop: li.cancel(true); break; } } } class LoadImage extends AsyncTask<String, Integer, Bitmap> { //开始执行耗时操作,连接网络获取图片,并且将Bitmap返回 @Override protected Bitmap doInBackground(String... params) { int i = 0; while (true) { if (i > 100) { break; } i++; try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } Log.d("TTTT","" + i); publishProgress(i); } String url = params[0]; Bitmap bitmap = null; URLConnection connection; InputStream is; try { connection = new URL(url).openConnection(); is = connection.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); bitmap = BitmapFactory.decodeStream(bis); is.close(); bis.close(); } catch (IOException e) { e.printStackTrace(); } return bitmap; } //onPreExcute方法是在doInBackGround方法前执行,用于做一些初始化操作,这里将progressBar显示出来 @Override protected void onPreExecute() { super.onPreExecute(); progressBar.setVisibility(View.VISIBLE); } //doInBackGround方法执行后,会自动执行该方法,获取到doInBackGround返回的对象,然后更改UI @Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); progressBar.setVisibility(View.GONE); imageView.setImageBitmap(bitmap); } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); progressBar.setProgress(values[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 onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //获取组件 btStart = (Button) findViewById(R.id.btStart); btStop = (Button) findViewById(R.id.btStop); imageView = (ImageView) findViewById(R.id.imageView); progressBar = (ProgressBar) findViewById(R.id.progressBar); //给button设置点击事件,点击按钮,启动异步任务 MyOnClickListener moc = new MyOnClickListener(); btStart.setOnClickListener(moc); btStop.setOnClickListener(moc); } class MyOnClickListener implements View.OnClickListener { LoadImage li = new LoadImage(); @Override public void onClick(View v) { switch (v.getId()){ case R.id.btStart: li.execute(URL); break; case R.id.btStop: li.cancel(true); break; } } } class LoadImage extends AsyncTask<String, Integer, Bitmap> { //开始执行耗时操作,连接网络获取图片,并且将Bitmap返回 @Override protected Bitmap doInBackground(String... params) { int i = 0; while (true) { if (i > 100) { break; } if (isCancelled()){ break; } i++; try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } Log.d("TTTT","" + i); publishProgress(i); } String url = params[0]; Bitmap bitmap = null; URLConnection connection; InputStream is; try { connection = new URL(url).openConnection(); is = connection.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); bitmap = BitmapFactory.decodeStream(bis); is.close(); bis.close(); } catch (IOException e) { e.printStackTrace(); } return bitmap; } //onPreExcute方法是在doInBackGround方法前执行,用于做一些初始化操作,这里将progressBar显示出来 @Override protected void onPreExecute() { super.onPreExecute(); progressBar.setVisibility(View.VISIBLE); } //doInBackGround方法执行后,会自动执行该方法,获取到doInBackGround返回的对象,然后更改UI @Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); progressBar.setVisibility(View.GONE); imageView.setImageBitmap(bitmap); } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); progressBar.setProgress(values[0]); } } }
cancel