自己写的Android 异步任务加载图片代码

public class DownloadImageTask extends AsyncTask<String, Void, Bitmap>{private static final String TAG = "DownloadImageTask";private String url;private ImageView imageViewReference;public DownloadImageTask(ImageView imageView){imageViewReference = imageView;}@Overrideprotected Bitmap doInBackground(String... params){// TODO Auto-generated method stubLog.d(TAG, "thumb_image_url:" + params[0]);url = params[0];return downloadBitmap(url);}@Overrideprotected void onPostExecute(Bitmap bitmap){// BitmapDrawable drawable=BitmapDrawable.// TODO Auto-generated method stubif (imageViewReference != null){imageViewReference.setImageBitmap(bitmap);}}Bitmap downloadBitmap(String url){final int IO_BUFFER_SIZE = 4 * 1024;final HttpClient client = new DefaultHttpClient();// : AndroidHttpClient.newInstance("Android");final HttpGet getRequest = new HttpGet(url);try{HttpResponse response = client.execute(getRequest);final int statusCode = response.getStatusLine().getStatusCode();if (statusCode != HttpStatus.SC_OK){Log.v("ImageDownloader", "Error" + statusCode + "while restrieving bitmap from" + url);return null;}final HttpEntity entity = response.getEntity();if (entity != null){InputStream inputStream = null;try{inputStream = entity.getContent();return BitmapFactory.decodeStream(inputStream);} finally{if (inputStream != null){inputStream.close();}entity.consumeContent();}}} catch (IOException e){getRequest.abort();Log.v(TAG, "I/O error while retrieving bitmap from " + url, e);} catch (IllegalStateException e){getRequest.abort();Log.w(TAG, "Incorrect URL: " + url);} catch (Exception e){getRequest.abort();Log.w(TAG, "Error while retrieving bitmap from " + url, e);} finally{if ((client instanceof AndroidHttpClient)){((AndroidHttpClient) client).close();}}return null;}}

更多相关文章

  1. Android常用功能代码总结一
  2. android在java代码中绘制矩形框
  3. 用ant实现自动打包android(二) -- android代码混淆
  4. Android通过WebView调用 JS 代码
  5. Android下为自己定义WifiManager类wifi模块代码
  6. android 加载模式
  7. 如何提高android代码质量
  8. Android日志系统Logcat源代码简要分析
  9. osg for android (一) 简单几何物体的加载与显示

随机推荐

  1. Android 使用HttpGet进行登录
  2. [Android]Bluetooth Smart Android appli
  3. Android(安卓)Studio学习-连接真机测试教
  4. android之sqlite数据库初级
  5. Android 实现Xmpp工具类
  6. android表格数据移动功能
  7. Android仿优酷客户端图片左右滑动(自动滑
  8. 解析Android中的Context
  9. android 启动第三方APP的方式
  10. Android使用Toast显示提示信息