AsyncTask的用法
onPreExcute 执行后台耗时操作前被调用,通常用户完成一些初始化动作
doInBackground 必须重写,异步执行后台线程将要完成的任务,不能在这方法中更新UI
onPostExecute 当doInBackground()完成后,系统会自动调用onPostExecute()方法,并将doInBackground()方法返回的值传递给该方法
onProgressUpdate 在doInBackground()方法中调用publishProgress()方法,更新任务的执行进度后,就会触发该方法(更新进度用publishProgress()方法)
注:执行异步操作在doInBackground中完成,获取网络图片
AsyncTask执行任务时是单线程,会造成一个任务正在执行时退出,之后在进入时要把先前的任务执行完成时才能执行新任务,解决办法是把Activity和AsyncTask同步,在onPause中标记AsyncTask取消为真(只是标记取消为真,Android中不能粗暴停止任务),之后在doInBackground和onProgressUpdate中判断(以进度条为例)
urlConnection=new URL(url).openConnection();/*通过openConnection()获取URLConnection对象*/ in=urlConnection.getInputStream();/*得到输入流对象*/ Thread.sleep(3000); BufferedInputStream buf=new BufferedInputStream(in);/*转换为缓冲输入流对象*/ bitmap= BitmapFactory.decodeStream(buf);/*通过BitmapFactory.decodeStream(buf)方法,得到bitmap对象*/ in.close(); buf.close();
接收网络图片
ImageActivity类
1 package asysnctaskdemo.example.administrator.asynctaskdemo; 2 3 import android.app.Activity; 4 import android.graphics.Bitmap; 5 import android.graphics.BitmapFactory; 6 import android.os.AsyncTask; 7 import android.os.Bundle; 8 import android.view.View; 9 import android.widget.ImageView; 10 import android.widget.ProgressBar; 11 12 import java.io.BufferedInputStream; 13 import java.io.IOException; 14 import java.io.InputStream; 15 import java.net.URL; 16 import java.net.URLConnection; 17 18 /** 19 * Created by Administrator on 2016/5/11. 20 */ 21 public class ImageActivity extends Activity { 22 private ImageView mImageView; 23 private ProgressBar mProgressBar; 24 private static String Url="http://pic3.zhongsou.com/image/38063b6d7defc892894.jpg"; 25 @Override 26 protected void onCreate(Bundle savedInstanceState) { 27 super.onCreate(savedInstanceState); 28 setContentView(R.layout.image); 29 mImageView= (ImageView) findViewById(R.id.image); 30 mProgressBar= (ProgressBar) findViewById(R.id.progressbar); 31 new MyAsyncTask().execute(Url); 32 } 33 class MyAsyncTask extends AsyncTask<String,Void,Bitmap>{/*接收三个参数*/ 34 InputStream in; 35 URLConnection urlConnection; 36 Bitmap bitmap; 37 38 @Override 39 protected void onPostExecute(Bitmap bitmap) { 40 super.onPostExecute(bitmap); 41 mProgressBar.setVisibility(View.GONE); 42 mImageView.setImageBitmap(bitmap); 43 } 44 45 @Override 46 protected void onPreExecute() { 47 super.onPreExecute(); 48 mProgressBar.setVisibility(View.VISIBLE); 49 } 50 51 @Override 52 protected Bitmap doInBackground(String... params) { 53 String url=params[0];/*获取输入对象*/ 54 try { 55 urlConnection=new URL(url).openConnection();/*通过openConnection()获取URLConnection对象*/ 56 in=urlConnection.getInputStream();/*得到输入流对象*/ 57 Thread.sleep(3000); 58 BufferedInputStream buf=new BufferedInputStream(in);/*转换为缓冲输入流对象*/ 59 bitmap= BitmapFactory.decodeStream(buf);/*通过BitmapFactory.decodeStream(buf)方法,得到bitmap对象*/ 60 in.close(); 61 buf.close(); 62 63 64 } catch (IOException e) { 65 e.printStackTrace(); 66 } catch (InterruptedException e) { 67 e.printStackTrace(); 68 } 69 return bitmap; 70 } 71 } 72 }
image.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:padding="10dp"> 6 <ImageView 7 android:layout_width="match_parent" 8 android:layout_height="match_parent" 9 android:id="@+id/image"/> 10 <ProgressBar 11 android:layout_centerInParent="true" 12 android:visibility="gone" 13 android:layout_width="wrap_content" 14 android:layout_height="wrap_content" 15 android:id="@+id/progressbar"/> 16 17 </RelativeLayout>
activity_main.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:tools="http://schemas.android.com/tools" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 android:orientation="vertical" 7 > 8 9 10 <Button 11 android:id="@+id/button2" 12 android:layout_width="match_parent" 13 android:layout_height="wrap_content" 14 android:text="更新进度" 15 android:onClick="loadImage2"/> 16 <Button 17 android:id="@+id/button" 18 android:layout_width="match_parent" 19 android:layout_height="wrap_content" 20 android:text="点击" 21 android:onClick="loadImage"/> 22 23 </LinearLayout>
MainActivity代码
1 package asysnctaskdemo.example.administrator.asynctaskdemo; 2 3 import android.content.Intent; 4 import android.support.v7.app.AppCompatActivity; 5 import android.os.Bundle; 6 import android.view.View; 7 import android.widget.Button; 8 9 public class MainActivity extends AppCompatActivity { 10 private Button button; 11 private Button button2; 12 @Override 13 protected void onCreate(Bundle savedInstanceState) { 14 super.onCreate(savedInstanceState); 15 setContentView(R.layout.activity_main); 16 MyAsyncTask myAsyncTask = new MyAsyncTask(); 17 myAsyncTask.execute(); 18 button= (Button) findViewById(R.id.button); 19 button2= (Button) findViewById(R.id.button2); 20 button2.setOnClickListener(new View.OnClickListener() { 21 @Override 22 public void onClick(View v) { 23 Intent intent2=new Intent(MainActivity.this,ProgressBarDemo.class); 24 startActivity(intent2); 25 } 26 }); 27 button.setOnClickListener(new View.OnClickListener() { 28 @Override 29 public void onClick(View v) { 30 Intent intent=new Intent(MainActivity.this,ImageActivity.class); 31 startActivity(intent); 32 33 } 34 }); 35 } 36 /* public void loadImage(View view) { 37 startActivity(new Intent(this, ImageActivity.class)); 38 }*/ 39 }
更新进度条
ProgressBarDemo类
1 import android.app.Activity; 2 import android.os.AsyncTask; 3 import android.os.Bundle; 4 import android.widget.ProgressBar; 5 6 /** 7 * Created by Administrator on 2016/5/11. 8 */ 9 public class ProgressBarDemo extends Activity { 10 ProgressBar mProgressBar; 11 MyAsyncTask myTask=new MyAsyncTask(); 12 @Override 13 protected void onCreate(Bundle savedInstanceState) { 14 super.onCreate(savedInstanceState); 15 setContentView(R.layout.progress); 16 mProgressBar= (ProgressBar) findViewById(R.id.progressbar2); 17 myTask=new MyAsyncTask(); 18 myTask.execute(); 19 } 20 21 @Override 22 protected void onPause() { 23 super.onPause(); 24 if(myTask!=null&&myTask.getStatus()==AsyncTask.Status.RUNNING){ 25 myTask.cancel(true);/*只是把myTask标记为取消状态,没有真正取消*/ 26 } 27 } 28 29 class MyAsyncTask extends AsyncTask<Void,Integer,Void>{ 30 @Override 31 protected Void doInBackground(Void... params) { 32 for (int i=0;i<100;i++){ 33 if(isCancelled()){ 34 break; 35 } 36 publishProgress(i); 37 try { 38 Thread.sleep(300); 39 } catch (InterruptedException e) { 40 e.printStackTrace(); 41 } 42 } 43 return null; 44 } 45 46 @Override 47 protected void onProgressUpdate(Integer... values) { 48 mProgressBar.setProgress(values[0]); 49 if (isCancelled()){ 50 return; 51 } 52 super.onProgressUpdate(values); 53 } 54 55 56 } 57 }
progress.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:orientation="vertical" android:layout_width="match_parent" 4 android:layout_height="match_parent"> 5 <ProgressBar 6 android:layout_gravity="center_horizontal" 7 style="?android:progressBarStyleHorizontal" 8 android:layout_width="match_parent" 9 android:layout_height="wrap_content" 10 android:id="@+id/progressbar2"/> 11 </LinearLayout>