封裝Android加載網絡圖片

直接貼代碼吧


<pre name="code" class="java">/**
 * 工具類,用於獲得要加載的圖片資源
 * 
 * @author LangK
 * 
 */

public class ImageHelper extends AsyncTask<String, Void, String> {
	private static final String TAG = ImageHelper.class;
	ImageView imageView;
	private Context mContext;
	private String webServerStr;
        //本地路徑
	private String localfile = Environment.getExternalStorageDirectory()
			.getPath() + "/packename/image";
	private String imageName;

	public ImageHelper(ImageView imageView, Context mContext) {
		// TODO Auto-generated constructor stub
		this.imageView = imageView;
		this.mContext = mContext;
               //網絡圖片路徑的前綴,沒有可以設爲空“”
		this.webServerStr = HttpUtil.IMAGESERVER;
	}

	@Override
	protected String doInBackground(String... urls) {
		String result = null;
		imageName = urls[0];
		if (imageName==null||imageName.equals("")) {
			return "";
		}
		HttpURLConnection connection = null;
		InputStream is = null;
		RandomAccessFile randomAccessFile = null;
		if (Util.isSDCardExist()) {
			try {
				File file = new File(localfile);
				if (!file.exists()) {
					file.mkdirs();
				}
				String localfilepath = localfile + "/" + imageName;

				file = new File(localfilepath);
				if (file.exists()) {
					return file.getAbsolutePath();
				}
				
				String encodedURL = URLEncoder.encode(imageName, "UTF-8");
				String urlStr = webServerStr + encodedURL;
				Log.d(TAG, "文件下載地址:" + urlStr.toString());
				URL url = new URL(urlStr);
				connection = (HttpURLConnection) url.openConnection();
				connection.setConnectTimeout(5000);
				connection.setRequestMethod("GET");
				long fileSize = connection.getContentLength();
				int responseCode = connection.getResponseCode();
				Log.d(TAG, "文件下載狀態碼"+responseCode);
				if (fileSize==0||responseCode!=200) {
					if (connection!=null) {
						connection.disconnect();
					}
					return "";
				}
				
				// 將要下載的文件寫到保存在保存路徑下的文件中
				randomAccessFile = new RandomAccessFile(localfilepath, "rwd");
				is = connection.getInputStream();
				if (is != null) {
					byte[] buffer = new byte[4096];
					int length = -1;
					while ((length = is.read(buffer)) != -1) {
						randomAccessFile.write(buffer, 0, length);
					}
					Log.d(TAG, "下載" + imageName + "文件成功");
				}
				result = file.getAbsolutePath();
			} catch (Exception e) {
				// result = false;
				Log.d(TAG, imageName + "下載文件出現異常", e);
				e.printStackTrace();
			} finally {
				try {
					if (is != null) {
						is.close();
						is=null;
					}
					if (randomAccessFile!=null) {
						randomAccessFile.close();
						randomAccessFile=null;
					}
					if (connection!=null) {
						connection.disconnect();
					}
				} catch (Exception e) {
					Log.d(TAG, imageName + "關閉文件出現異常", e);
					e.printStackTrace();
				}
			}
		} else {
			Log.d(TAG, "SD卡不存在,請檢查SD卡是否插好");
		}

		return result;
	}

	/**
	 * 獲取下載好的圖片
	 */
	@Override
	protected void onPostExecute(String result) {
		BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
		bitmapOptions.inSampleSize = 2;
//		bitmapOptions.inJustDecodeBounds= true;
		if (result == null||result.equals("")) {
			if (imageView != null) {
				imageView.setBackgroundResource(R.drawable.ztephone);
			}
		} else {
			if (imageView != null) {
//				int windowWidth = mContext.getResources().getDisplayMetrics().widthPixels;
				Bitmap map = null;
				map = BitmapFactory.decodeFile(result,bitmapOptions);
				if (map==null) {
					imageView.setBackgroundResource(R.drawable.ztephone);
				}else {
	//				int imageWidth = map.getWidth();
	//				int imageHeight = map.getHeight();
	//				map = BitmapUtil.zoomImg(map, imageWidth * windowWidth
	//						/ imageWidth, imageHeight * windowWidth / imageWidth);
					imageView.setImageBitmap(map);
				}
			}
		}
	}
}

}}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章