原文地址
http://bbs.isgphone.com/viewthread.php?tid=5455
请支持原创
上次我们讲到了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); 即可。
- 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;
- }
- 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();
- }
- }