1. 程式人生 > >Android 非同步獲取網路圖片Bitmap資源

Android 非同步獲取網路圖片Bitmap資源

這裡主要是為了把獲取圖片的程式碼單獨出來和UI分開,方便擴充套件。

public interface Callback<T> {
  	public void onSuccess(T obj);
	public void onError(String error);
}
執行緒執行結束後,回撥介面,成功後呼叫onSuccess方法T為通用型別引數,錯誤呼叫onError
public class GetBitmapResControl {

	private Activity activity;

	public GetBitmapResControl(Activity activity) {
		this.activity = activity;
	}

	public void doGetBitmap(final String url, final Callback<ImageView> callBack) {
		new Thread() {
			public void run() {
				byte b[] = null;
				try {
					String _data = getImageData(url);//我這裡的測試圖片傳入的是base64內容格式的.
					if (_data != null) {
						b = Base64Util.decode(_data);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				final Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
				activity.runOnUiThread(new Runnable() {
					public void run() {
						if (bitmap == null) {
							callBack.onError("獲取圖片失敗");
						} else {
							ImageView img = new ImageView(activity);
							img.setImageBitmap(bitmap);
						        callBack.onSuccess(img);
						}
					}
				});
			};
		}.start();
	}
        //獲取網路中的圖片內容
	private String getImageData(String url) throws ClientProtocolException, IOException {
 		Log.d("getImageData", "URL:" + url);
		org.apache.http.client.HttpClient client = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(url);
		HttpResponse httpResponse = client.execute(httpget);
		int status = httpResponse.getStatusLine().getStatusCode();
		if (status == HttpStatus.SC_OK) {
			Log.d("getImageData", "status:" + status);
			String strResult = EntityUtils.toString(httpResponse.getEntity());
			return strResult;
		}
		return null;
	}

}

在Activity 中呼叫

		new GetBitmapResControl(this).doGetBitmap("http://x.x.x.x/server/getimg?id=12", new Callback<ImageView>() {
			@Override
			public void onSuccess(ImageView obj) {
				rootView.addView(obj);
			}
			
			@Override
			public void onError(String error) {
				Toast.makeText(getApplicationContext(), error, Toast.LENGTH_SHORT).show();
			}
		});