一、创建异步任务
public class LoadBitmapAsyn extends AsyncTask<String,Void,Bitmap> { Context context; ImageView img; private HashMap<String,SoftReference<Bitmap>> imageCache=null; public LoadBitmapAsyn(ImageView img){ this.img=img; this.context=context; } @Override protected void onPreExecute() { super.onPreExecute(); imageCache=new HashMap<String,SoftReference<Bitmap>>(); } @Override protected Bitmap doInBackground(String... strings) { try {
//获取到网络数据,返回bitmap InputStream in = new URL(strings[0]).openStream(); Bitmap bitmap1 = BitmapFactory.decodeStream(in); //存储到手机内存的指定位置 File dir = new File(Environment.getExternalStorageDirectory() + "/test/"); if (!dir.exists()) { dir.mkdirs(); } File bitmapFile = new File(Environment.getExternalStorageDirectory() + "/test/" + strings[0].substring(strings[0].lastIndexOf("/") + 1)); if (!bitmapFile.exists()) { try { bitmapFile.createNewFile(); } catch (IOException e) { //TODOAuto-generatedcatchblock e.printStackTrace(); } } FileOutputStream fos; try { fos = new FileOutputStream(bitmapFile); bitmap1.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bitmap1; } catch (Exception e) { int i = 1 + 1; } return null; } @Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); img.setImageBitmap(bitmap); } } 二、activity中检测缓存中是否有盖图片,优先加载内存缓存,其次是内部存储,最后才是网上下载
//检测缓存和内存中是否有指定路径名的bitmap数据
public Bitmap loadBitmap(final String imageURL){ imageCache=new HashMap<String,SoftReference<Bitmap>>(); //在内存缓存中,则返回Bitmap对象 if (imageCache.containsKey(imageURL)) { SoftReference<Bitmap> reference = imageCache.get(imageURL); Bitmap bitmap = reference.get(); if (bitmap != null) { return bitmap; } } else { /** *加上一个对本地缓存的查找 */
//提取图片名字 String bitmapName = imageURL.substring(imageURL.lastIndexOf("/") + 1); File cacheDir = new File(Environment.getExternalStorageDirectory()+"/test/"); File[] cacheFiles = cacheDir.listFiles(); int i = 0; if (null != cacheFiles) { for (; i < cacheFiles.length; i++) { if (bitmapName.equals(cacheFiles[i].getName())) { break; } } if (i < cacheFiles.length) { return BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/test/" + bitmapName); } } } return null; }
三、activity中的调用
Bitmap bitmap = loadBitmap(url);ImageView img = new ImageView(yourActivity);if (bitmap2 != null) { img.setImageBitmap(bitmap2); } else { LoadBitmapAsyn loadBitmapAsyn = new LoadBitmapAsyn(imageView); loadBitmapAsyn.execute(url); }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-29 20:43:43