这里主要是为了把获取图片的代码单独出来和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();
}
});