关闭

AsyncTask 异步任务

81人阅读 评论(0) 收藏 举报
分类:

一、AsyncTask的介绍

Android的AsyncTask比Handler更轻量级一些,适用于简单的异步处理。

Android之所以有AsyncTask和Handler都是为了不阻塞主线程,且UI的更新只能在主线程中完成,因此异步处理是必不可少的。Android为了减少这个开发难度,提供了AsyncTask。AsyncTask就是一个封装过的后台任务类。

AsyncTask直接继承于Object类,位置为android.os.AsyncTask。要使用AsyncTask我们要提供三个泛型参数,并重载几个方法(至少一个)。

AsyncTask定义了三种泛型类参数:Params,Progress和Result。

Params 启动任务执行的输入的参数,如HTTP请求的URL。

Progress 后台执行任务的百分比。如进度加载

Resu 后台任务执行最终返回的结果。

AsyncTask的几个方法的详解:

doInBackground(Params... params)后台执行,比较耗时的操作都可以放在这个方法里面。注意这里不能直接操作UI。在执行过程中可以调用onProgressUpdate(Progress... values)方法来更新任务的进度。

onProgressUpdate(Progress... values)  相当于Handler处理UI的方式。在这里可以使用在doInBackground()得到的结果处理UI。此方法在主线程执行

onPostExecute(String result)后台执行,在这里处理doInBackground()方法执行完后返回的结果,在这里也可以对UI控件进行更新

二、AsyncTask的使用

如下实例1:模仿下载进度

Java代码:

public class MyAsnycTaskActivity extends Activity implements OnClickListener{
	private Button mStartBtn;
	private SeekBar mProgressSeekBar;
	private TextView mCurrentProgressTxt;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_asnyctask_layout);
		mStartBtn = (Button) findViewById(R.id.asnyctask_start_btn);
		mProgressSeekBar = (SeekBar) findViewById(R.id.asnyctask_progress_sekbar);
		mCurrentProgressTxt = (TextView) findViewById(R.id.asnyctask_current_progress_txt);
		mStartBtn.setOnClickListener(this);
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.asnyctask_start_btn:
			MyAsnycTask asnycTask = new MyAsnycTask();
			asnycTask.execute();
			break;
		default:
			break;
		}
	}<pre name="code" class="java"><span style="white-space:pre">	</span>/**
<span>	</span> * AsyncTask<String, Integer, String>
<span>	</span> * Params 第一个参数: 传入异步任务中的数据类型
<span>	</span> * Progress 第二个参数:  异步任务执行过程中发送数据类型
<span>	</span> * Result  第三个参数:   异步任务执行完成后返回数据类型
<span>	</span> * 
<span>	</span> * 注:如果类型为 Void  表示没有参数
<span>	</span> */


	public class MyAsnycTask extends AsyncTask<Void, Integer, String>{
<span style="white-space:pre">		/**
<span style="white-space:pre">		</span> * 执行异步任务前调用方法
<span style="white-space:pre">		</span> */
<span style="white-space:pre">		</span>@Override
<span style="white-space:pre">		</span>protected void onPreExecute() {
<span style="white-space:pre">			</span>super.onPreExecute();
<span style="white-space:pre">			</span>Logs.v("onPreExecute >>>>>> ");
<span style="white-space:pre">		</span>}</span>
<span style="white-space:pre">		/**
<span style="white-space:pre">		</span> * 后台(子线程)执行异步任务
<span style="white-space:pre">		</span> */</span>
		@Override
		protected String doInBackground(Void... params) {
			for (int i = 1; i <= 100; i++) {
				publishProgress(i);
				mProgressSeekBar.setProgress(i);
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			String result = "加载完成";
			return result;
		}
		/**
<span style="white-space:pre">		</span> * 异步任务执行过程中调用方法.
<span style="white-space:pre">		</span> * 必须在doInBackground方法中调用publishProgress()方法发送消息
<span style="white-space:pre">		</span> */
		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			int progress = values[0];
			
			mCurrentProgressTxt.setText(""+progress);
		}
		/**
<span style="white-space:pre">		</span> * 异步任务执行完成后调用方法
<span style="white-space:pre">		</span> */
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			Toast.makeText(MyAsnycTaskActivity.this, result, Toast.LENGTH_SHORT).show();
			mCurrentProgressTxt.setText(result);
		}
	}
}

运行效果如图:


实例应用2:网络下载图片

Java代码:

public class LoadPictureActivity extends Activity {
	
	private ImageView mPictureImg;
	private Button mDownLoadBtn;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.async_load_picture_layout);
		
		mPictureImg = (ImageView) findViewById(R.id.async_picture_img);
		mDownLoadBtn = (Button) findViewById(R.id.async_load_picture_btn);
		
		mDownLoadBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String httpUrl = "http://img2.imgtn.bdimg.com/it/u=94536769,318259447&fm=23&gp=0.jpg";
				
//				MyAsyncTask sycn = new MyAsyncTask();
//				sycn.execute(httpUrl);
				
				new AsyncTask<String, Void, Bitmap>(){

					@Override
					protected Bitmap doInBackground(String... params) {
						return downLoadPicture(params[0]);
					}
					
					protected void onPostExecute(Bitmap result) {
						mPictureImg.setImageBitmap(result);
					}
				}.execute(httpUrl);
			}
		});
	}
	/**
	 * 网络下载图片
	 * @param url: http://xxx.png
	 */
	public Bitmap downLoadPicture(String httpUrl){
		try {
			URL url = new URL(httpUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			InputStream is = conn.getInputStream();
			
			Bitmap bitmap = BitmapFactory.decodeStream(is);
			
			return bitmap;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
		
	}
	public class MyAsyncTask extends AsyncTask<String, Void, Bitmap>{
		@Override
		protected void onPostExecute(Bitmap result) {
			super.onPostExecute(result);
			Bitmap bitmap = result;
			mPictureImg.setImageBitmap(bitmap);
		}

		@Override
		protected Bitmap doInBackground(String... params) {
			String url = params[0];
			Bitmap bitmap = downLoadPicture(url);
			return bitmap;
		}
	}
}


实例应用3:GridView  AsyncTask异步任务取网络图片

Java代码:

public class GridViewAsyncTaskActivity extends Activity {
	private GridView mGridView;
	private String[] imageThumbUrls = new String[] {
			"http://img.my.csdn.net/uploads/201407/26/1406383299_1976.jpg",
			"http://img.my.csdn.net/uploads/201407/26/1406383291_6518.jpg",
			"http://img.my.csdn.net/uploads/201407/26/1406383291_8239.jpg",
			"http://img.my.csdn.net/uploads/201407/26/1406383290_9329.jpg",
			"http://img.my.csdn.net/uploads/201407/26/1406383290_1042.jpg",
			"http://img.my.csdn.net/uploads/201407/26/1406383275_3977.jpg",
			"http://img.my.csdn.net/uploads/201407/26/1406383265_8550.jpg",
			"http://img.my.csdn.net/uploads/201407/26/1406383264_3954.jpg",
			"http://img.my.csdn.net/uploads/201407/26/1406383264_4787.jpg",
		 };
	private GridViewAdapter mAdapter;
	private Executor mExecutor;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.asyn_grid_layout);
		mGridView = (GridView) findViewById(R.id.async_gridview);

		mAdapter = new GridViewAdapter(this);
		mGridView.setAdapter(mAdapter);
		/**按顺序<span style="color:#ff0000;">10/150/10</span>分别为:当前同时运行线程的个数;最多运行线程的个数;
		*线程请求超时
		*/
		<span style="color:#ff0000;">mExecutor</span> = new ThreadPoolExecutor(<span style="color:#ff0000;">10,  150, 10,</span>TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
	}
	/**
	 * 通过在异步任务中循环加载图片,不断刷新适配器实现
	 * 不提倡,原因:
	 * 1.重复刷新适配器执行getView方法 
	 * 2.不能实现图片同步加载,相当于当线程执行.
	 */
	public void loadPictureByPublishProgress(){
		new AsyncTask<String, Bitmap, Void>() {
			@Override
			protected Void doInBackground(String... params) {
				for (int i = 0; i < params.length; i++) {
					Bitmap bm = downLoadPicture(params[i]);
					publishProgress(bm);
				}
				return null;
			}
			protected void onProgressUpdate(Bitmap... values) {
//				mAdapter.addDate(values[0]);
			}
		}.execute(imageThumbUrls);
	}
	
	public class MyGridViewAdapter extends BaseAdapter {
		private ArrayList<Bitmap> list = new ArrayList<Bitmap>();
		private LayoutInflater infalter;
		public void addDate(Bitmap bm) {
			list.add(bm);
			notifyDataSetChanged();
		}
		public MyGridViewAdapter(Context context) {
			infalter = LayoutInflater.from(context);
		}
		@Override
		public int getCount() {
			return list.size();
		}
		@Override
		public Object getItem(int position) {
			return list.get(position);
		}
		@Override
		public long getItemId(int position) {
			return position;
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final ImageView imageview;
			if (convertView == null) {
				convertView = infalter.inflate(R.layout.async_gridview_item_layout, null);
				imageview = (ImageView) convertView.findViewById(R.id.async_item_img);
				convertView.setTag(imageview);
			} else {
				imageview = (ImageView) convertView.getTag();
			}
			Bitmap bitmap = (Bitmap) getItem(position);
			imageview.setImageBitmap(bitmap);
			return convertView;
		}
	}

	public class GridViewAdapter extends BaseAdapter {
		private LayoutInflater infalter;

		public GridViewAdapter(Context context) {
			infalter = LayoutInflater.from(context);
		}
		@Override
		public int getCount() {
			return imageThumbUrls.length;
		}
		@Override
		public Object getItem(int position) {
			return imageThumbUrls[position];
		}
		@Override
		public long getItemId(int position) {
			return position;
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final ImageView imageview;
			if (convertView == null) {
				convertView = infalter.inflate(
						R.layout.async_gridview_item_layout, null);
				imageview = (ImageView) convertView
						.findViewById(R.id.async_item_img);
				convertView.setTag(imageview);
			} else {
				imageview = (ImageView) convertView.getTag();
			}
			String httpUrl = (String) getItem(position);
			new AsyncTask<String, Void, Bitmap>() {
				@Override
				protected Bitmap doInBackground(String... params) {
					return downLoadPicture(params[0]);
				}

				protected void onPostExecute(Bitmap result) {
					if (result != null) {
						imageview.setImageBitmap(result);
					}
				}
			}.execute(httpUrl);  //单任务一个一个执行
//		    }.executeOnExecutor(<span style="color:#ff0000;">mExecutor</span>,httpUrl);  //多任务同时执行
			return convertView;
		}
	}
	/**
	 * 网络下载图片
	 * 
	 * @param url
	 */
	public Bitmap downLoadPicture(String httpUrl) {
		try {
			URL url = new URL(httpUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			InputStream is = conn.getInputStream();
			Bitmap bitmap = BitmapFactory.decodeStream(is);
			return bitmap;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:777次
    • 积分:74
    • 等级:
    • 排名:千里之外
    • 原创:7篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档