Android 异步任务加载图片代码
16lz
2021-01-23
自己写的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;}}
更多相关文章
- Android常用功能代码总结一
- android在java代码中绘制矩形框
- 用ant实现自动打包android(二) -- android代码混淆
- Android通过WebView调用 JS 代码
- Android下为自己定义WifiManager类wifi模块代码
- android 加载模式
- 如何提高android代码质量
- Android日志系统Logcat源代码简要分析
- osg for android (一) 简单几何物体的加载与显示