AsyncTask 实例代码演示Android 异步任务
上次我们讲到了Android 提供了一个较线程更简单的处理多任务的方法AsyncTask 异步任务类,相对于线程来说
AsyncTask 对于简单的任务处理更安全,其内部的实现方法使用了Android 的Handler 机制,对于常见的文件下载可以使用
AsyncTask 类来处理,在Browser 浏览器中就是用了该类下载Web 服务器URL 的Favicon 图标。首先Android123 以简单
的下载例子演示该类的大致结构,如下
private class DownloadFilesTask extends AsyncTask<url, integer,="" long=""> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls);
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<string, void,="" bitmap=""> {
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();
http://www.doczj.com/doc/f563ff3efe4733687e21aae8.htmlpress(http://www.doczj.com/doc/f563ff3efe4733687e21aae8.htmlpressFormat.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();
}
}