android缓存网络图片的方法
android的listview等控件都需要异步加载网络图片,可每次启动程序都要加载,应用就会显得很慢。
这时候,将图片保存到本地是个不错的提高应用加载速度的方法
private Bitmap CacheBitmap(String src)//获取Bitmap对象\r\n{\r\nFileHelper.CreateFolder(FileHelper.approot+"/cache");\r\nString burl="/cache/"+Common.MD5(src);\r\nBitmap mBitmap = null;\r\nFile f=new File(FileHelper.approot+ burl);\r\nif(f.exists())\r\n{\r\nFileInputStream fis;\r\ntry {\r\nfis = new FileInputStream(FileHelper.approot+ burl);\r\nmBitmap = BitmapFactory.decodeStream(fis);\r\n} catch (FileNotFoundException e) {\r\ne.printStackTrace();\r\n}\r\nLog.i("img","fromcache:"+burl);\r\n}\r\nelse\r\n{\r\ntry {\r\nURL url = new URL(src);\r\nHttpURLConnection conn = (HttpURLConnection) url.openConnection();\r\nInputStream is = conn.getInputStream();\r\nmBitmap = BitmapFactory.decodeStream(is);\r\nis.close();\r\nBufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f)); \r\nmBitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos); \r\n bos.flush(); \r\n bos.close();\r\n \r\n} catch (Exception e) {\r\nLog.i("img", "error:" + e.getClass());\r\n}\r\nLog.i("img","savecache:"+burl);\r\n}\r\nreturn mBitmap;\r\n}
FileHelper是一个io操作的类
public class FileHelper {\r\n public static String approot="";\r\n public static boolean Enable=false;\r\n public static void CreateFolder(String path)\r\n {\r\n File file = new File(path);\r\n if (!file.exists()) {\r\n file.mkdirs();\r\n }\r\n \r\n }\r\n \r\n public static void Load()\r\n {\r\n if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))\r\n {\r\n Enable=true;\r\n File f=Environment.getExternalStorageDirectory();\r\n approot=f.getPath();\r\n approot+="/yourapp";//app的文件目录\r\n File fr=new File(approot);\r\n if(!fr.exists())\r\n {\r\n fr.mkdirs();\r\n }\r\n }\r\n }\r\n}