AsyncTask執行個體代碼示範Android非同步任務

來源:互聯網
上載者:User
關鍵字: Android移動 嵌入式 移動開發 移動開發平台 Google移動

我們講到了Android提供了一個較線程更簡單的處理多任務的方法AsyncTask非同步任務類,相對於線程來說AsyncTask對於簡單的任務處理更安全,其內部的實現方法使用了Android的Handler機制,對於常見的檔案下載可以使用AsyncTask類來處理,在Browser瀏覽器中就是用了該類下載Web伺服器URL的Favicon表徵圖。

  首先Android123以簡單的下載例子示範該類的大致結構,如下

  private class DownloadFilesTask extends AsyncTask {

  protected Long doInBackground(URL... urls) {

  int count = urls.length;

  long totalSize = 0;

  for (int i = 0; i < count; i++) {

  totalSize += Downloader.downloadFile(urls[i]);

  publishProgress((int) ((i / (float) count)100));

  }

  return totalSize;

  }

  protected void onProgressUpdate(Integer... progress) {

  setProgressPercent(progress[0]);

  }

  protected void onPostExecute(Long result) {

  showDialog("Downloaded " + result + " bytes");

  }

  }

  最終我們執行 DownloadFilesTask().execute(url1, url2, url3); 即可。

  在Android瀏覽器中下載Favicon表徵圖的實現如下:

  class DownloadTouchIcon extends AsyncTask {

  private final ContentResolver mContentResolver;

  private final Cursor mCursor;

  private final String mOriginalUrl;

  private final String mUrl;

  private final String mUserAgent;

  /* package */ BrowserActivity mActivity;

  public DownloadTouchIcon(BrowserActivity activity, ContentResolver cr,

  Cursor c, WebView view) { //構造方法

  mActivity = activity;

  mContentResolver = cr;

  mCursor = c;

  mOriginalUrl = view.getOriginalUrl();

  mUrl = view.getUrl();

  mUserAgent = view.getSettings().getUserAgentString();

  }

  public DownloadTouchIcon(ContentResolver cr, Cursor c, String url) { //實現本類的構造

  mActivity = null;

  mContentResolver = cr;

  mCursor = c;

  mOriginalUrl = null;

  mUrl = url;

  mUserAgent = null;

  }

  @Override

  public Bitmap doInBackground(String... values) { //返回Bitmap類型

  String url = values[0];

  AndroidHttpClient client = AndroidHttpClient.newInstance(mUserAgent);

  HttpGet request = new HttpGet(url);

  HttpClientParams.setRedirecting(client.getParams(), true); //處理302等重新導向問題

  try {

  HttpResponse response = client.execute(request);

  if (response.getStatusLine().getStatusCode() == 200) { //如果OK

  HttpEntity entity = response.getEntity();

  if (entity != null) {

  InputStream content = entity.getContent(); //將表徵圖儲存到InputStream中,因為是二進位內容

  if (content != null) {

  Bitmap icon = BitmapFactory.decodeStream( //從流中取出Bitmap,這裡使用了BitmapFactory類的靜態方法decodeStream

  content, null, null);

  return icon;

  }

  }

  }

  } catch (IllegalArgumentException ex) {

  request.abort();

  } catch (IOException ex) {

  request.abort();

  } finally {

  client.close();

  }

  return null;

  }

  @Override

  protected void onCancelled() {

  if (mCursor != null) {

  mCursor.close();

  }

  }

  @Override

  public void onPostExecute(Bitmap icon) {

  if (mActivity != null) {

  mActivity.mTouchIconLoader = null;

  }

  if (icon == null || mCursor == null || isCancelled()) {

  return;

  }

  最終表徵圖要儲存到瀏覽器的內部資料庫中,系統程式均儲存為SQLite格式,Browser也不例外,因為圖片是二進位的所以使用位元組數組儲存資料庫的BLOB類型

  final ByteArrayOutputStream os = new ByteArrayOutputStream();

  icon.compress(Bitmap.CompressFormat.PNG, 100, os); //將Bitmap壓縮成PNG編碼,品質為100%儲存

  ContentValues values = new ContentValues(); //構造SQLite的Content對象,這裡也可以使用raw sql代替

  values.put(Browser.BookmarkColumns.TOUCH_ICON,os.toByteArray()); //寫入資料庫的Browser.BookmarkColumns.TOUCH_ICON欄位

  if (mCursor.moveToFirst()) {

  do {

  mContentResolver.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI, mCursor.getInt(0)),values, null, null);

  } while (mCursor.moveToNext());

  }

  mCursor.close();

  }

  }

  本次Android開發網通過兩個AsyncTask類示範了多種類型的任務構造,這裡大家注意傳回型別,本節示範了Android平台上 Content Provider、AsyncTask、Bitmap、HTTP以及Stream的相關操作,大家如何想很快提高開發水平其實只要理解Google如何去實現Android系統常規構架就可以輕鬆入門Google移動平台。

引用:http://mips.eefocus.com/article/10-08/1968501282623682.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.