AsyncTask实例代码演示Android异步任务

原文地址

http://bbs.isgphone.com/viewthread.php?tid=5455

请支持原创

上次我们讲到了Android提供了一个较线程更简单的处理多任务的方法AsyncTask异步任务类,相对于线程来说AsyncTask对于简单的任务处理更安全,其内部的实现方法使用了Android的Handler机制,对于常见的文件下载可以使用AsyncTask类来处理,在Browser浏览器中就是用了该类下载Web服务器URL的Favicon图标。

首先Android123以简单的下载例子演示该类的大致结构,如下

  1. private class DownloadFilesTask extends AsyncTask {   
  2.   protected Long doInBackground(URL... urls) {   
  3.   int count = urls.length;   
  4.   long totalSize = 0;   
  5.   for (int i = 0; i < count; i++) {   
  6.   totalSize += Downloader.downloadFile(urls[i]);   
  7.   publishProgress((int) ((i / (floatcount)100));   
  8.   }   
  9.   return totalSize;   
  10.   }   
  11.   protected void onProgressUpdate(Integer... progress) {   
  12.   setProgressPercent(progress[0]);   
  13.   }   
  14.   protected void onPostExecute(Long result) {   
  15.   showDialog("Downloaded " + result + " bytes");   
  16.   }   
  17.   }  

最终我们执行 DownloadFilesTask().execute(url1, url2, url3); 即可。

在Android浏览器中下载Favicon图标的实现如下:

  1. class DownloadTouchIcon extends AsyncTask {   
  2.   private final ContentResolver mContentResolver;   
  3.   private final Cursor mCursor;   
  4.   private final String mOriginalUrl;   
  5.   private final String mUrl;   
  6.   private final String mUserAgent;   
  7.   /* package */ BrowserActivity mActivity;   
  8.   public DownloadTouchIcon(BrowserActivity activity, ContentResolver cr,   
  9.   Cursor c, WebView view) { //构造方法   
  10.   mActivity = activity;   
  11.   mContentResolver = cr;   
  12.   mCursor = c;   
  13.   mOriginalUrl = view.getOriginalUrl();   
  14.   mUrl = view.getUrl();   
  15.   mUserAgent = view.getSettings().getUserAgentString();   
  16.   }   
  17.   public DownloadTouchIcon(ContentResolver cr, Cursor c, String url) { //实现本类的构造   
  18.   mActivity = null;   
  19.   mContentResolver = cr;   
  20.   mCursor = c;   
  21.   mOriginalUrl = null;   
  22.   mUrl = url;   
  23.   mUserAgent = null;   
  24.   }   
  25.   @Override   
  26.   public Bitmap doInBackground(String... values) { //返回Bitmap类型   
  27.   String url = values[0];   
  28.   AndroidHttpClient client = AndroidHttpClient.newInstance(mUserAgent);   
  29.   HttpGet request = new HttpGet(url);   
  30.   HttpClientParams.setRedirecting(client.getParams(), true); //处理302等重定向问题   
  31.   try {   
  32.   HttpResponse response = client.execute(request);   
  33.   if (response.getStatusLine().getStatusCode() == 200) { //如果OK   
  34.   HttpEntity entity = response.getEntity();   
  35.   if (entity != null) {   
  36.   InputStream content = entity.getContent(); //将图标保存到InputStream中,因为是二进制内容   
  37.   if (content != null) {   
  38.   Bitmap icon = BitmapFactory.decodeStream( //从流中取出Bitmap,这里使用了BitmapFactory类的静态方法decodeStream   
  39.   content, nullnull);   
  40.   return icon;   
  41.   }   
  42.   }   
  43.   }   
  44.   } catch (IllegalArgumentException ex) {   
  45.   request.abort();   
  46.   } catch (IOException ex) {   
  47.   request.abort();   
  48.   } finally {   
  49.   client.close();   
  50.   }   
  51.   return null;   
  52.   }   
  53.   @Override   
  54.   protected void onCancelled() {   
  55.   if (mCursor != null) {   
  56.   mCursor.close();   
  57.   }   
  58.   }   
  59.   @Override   
  60.   public void onPostExecute(Bitmap icon) {   
  61.   if (mActivity != null) {   
  62.   mActivity.mTouchIconLoader = null;   
  63.   }   
  64.   if (icon == null || mCursor == null || isCancelled()) {   
  65.   return;   
  66.   }  

最终图标要保存到浏览器的内部数据库中,系统程序均保存为SQLite格式,Browser也不例外,因为图片是二进制的所以使用字节数组存储数据库的BLOB类型

  1. final ByteArrayOutputStream os = new ByteArrayOutputStream();   
  2.   icon.compress(Bitmap.CompressFormat.PNG, 100, os); //将Bitmap压缩成PNG编码,质量为100%存储   
  3.   ContentValues values = new ContentValues(); //构造SQLite的Content对象,这里也可以使用raw sql代替   
  4.   values.put(Browser.BookmarkColumns.TOUCH_ICON,os.toByteArray()); //写入数据库的Browser.BookmarkColumns.TOUCH_ICON字段   
  5.   if (mCursor.moveToFirst()) {   
  6.   do {   
  7.   mContentResolver.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI, mCursor.getInt(0)),valuesnullnull);   
  8.   } while (mCursor.moveToNext());   
  9.   }   
  10.   mCursor.close();   
  11.   }   
  12.   }  

本次Android开发网通过两个AsyncTask类演示了多种类型的任务构造,这里大家注意返回类型,本节演示了Android平台上Content Provider、AsyncTask、Bitmap、HTTP以及Stream的相关操作,大家如何想很快提高开发水平其实只要理解Google如何去实现Android系统常规构架就可以轻松入门谷歌移动平台。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章