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();
			}
		});