首先发起一个网络请求,请求到图片的url后再去请求图片。
请求图片后返回到主线程处理
private Runnable myRun;
private DefaultHttpClient httpClient;
private Object result;
public void request(final String url) {
Log.i("mjm", "request : " + url);
myRun = new Runnable() {
@Override
public void run() {
Log.i("TAG", url);
httpClient = new DefaultHttpClient();
// 设置网络连接超时时间
httpClient.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
// 设置网络socket通信超时时间
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
3000);
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse;
try {
httpResponse = httpClient.execute(httpGet);
int code = httpResponse.getStatusLine().getStatusCode();
// 请求成功
if (HttpStatus.SC_OK == code) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
httpResponse.getEntity().writeTo(baos);
result = new String(baos.toByteArray()).trim();
Log.i("TAG", result.toString());
loadImageFromUrl(result.toString());
} else {// 请求失败
httpGet.abort();
result = "fail";
Log.i("TAG", result.toString());
}
} catch (Exception e) {// 解码异常
e.printStackTrace();
}
}
};
new Thread(myRun).start();
}
public void loadImageFromUrl(final String url) {
Log.i("mjm", "loadImageFromUrl : " + url);
myRun = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Bitmap bitmap = null;
URL u = null;
HttpURLConnection conn = null;
InputStream is = null;
try {
u = new URL(url);
conn = (HttpURLConnection) u.openConnection();
is = conn.getInputStream();
Log.i("mjm", "is : " + is.toString());
bitmap = BitmapFactory.decodeStream(is);
mLoadImageCallBack.onSuccess(bitmap);
} catch (Exception e) {
Log.i("mjm", "false : " + e.toString());
mLoadImageCallBack.onFail(e.toString());
}
}
};
new Thread(myRun).start();
}
原文:http://www.cnblogs.com/moreking/p/4312204.html