閱讀117 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Android中獲取網絡圖片的方法(如果手機緩存裏麵有就從緩存獲取)

https://doinone.iteye.com/blog/1074366



// 如果緩存裏麵有就從緩存獲取,否則網絡獲取圖片,返回Drawable對象
	public static Drawable loadImageFromNetwork(Context context, String imageUrl)
	{
		Drawable drawable = null;
		if(imageUrl == null )
			return null;
		String imagePath = "";
		String   fileName   = "";
			
		// 獲取url中圖片的文件名與後綴
		if(imageUrl!=null&&imageUrl.length()!=0){ 
            fileName  = imageUrl.substring(imageUrl.lastIndexOf("/")+1);
		}
		
		// 圖片在手機本地的存放路徑,注意:fileName為空的情況
		imagePath = context.getCacheDir() + "/" + fileName;

		Log.i("test","imagePath = " + imagePath);
		File file = new File(context.getCacheDir(),fileName);// 保存文件
		Log.i("test","file.toString()=" + file.toString());
		if(!file.exists()&&!file.isDirectory())
		{
			try {
				// 可以在這裏通過文件名來判斷,是否本地有此圖片
				
				FileOutputStream   fos=new   FileOutputStream( file );
				InputStream is = new URL(imageUrl).openStream();
				int   data = is.read(); 
				while(data!=-1){ 
				        fos.write(data); 
				        data=is.read();; 
				} 
				fos.close();
				is.close();
//				drawable = Drawable.createFromStream(
//						new URL(imageUrl).openStream(), file.toString() ); // (InputStream) new URL(imageUrl).getContent();
				drawable = Drawable.createFromPath(file.toString());
				Log.i("test", "file.exists()不文件存在,網上下載:" + drawable.toString());
			} catch (IOException e) {
				Log.d("test", e.getMessage());
			}
		}else
		{
			drawable = Drawable.createFromPath(file.toString());
			Log.i("test", "file.exists()文件存在,本地獲取");
		}
		
		if (drawable == null) {
			Log.d("test", "null drawable");
		} else {
			Log.d("test", "not null drawable");
		}
		
		return drawable ;
	}


最後更新:2017-04-02 22:16:38

  上一篇:go Eclipse文件轉碼插件
  下一篇:go 軟件框架設計之美