从网路获取图片,使用AsyncTask异步通信。
异步代码如下:
public void addTask(String url) {
new AsyncTask<String, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(String... params) {
// 后台通信
return decodeBitmap(params[0]);
// return byteBitmap(params[0]);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
// 主线程处理view
if (bitmap != null) {
mTestImage.setImageBitmap(bitmap);
}
}
}.execute(url);
}
后台处理方法
方法一:使用 BitmapdecodeStream(InputStream is)
private Bitmap decodeBitmap(String httpUrl) {
URL url = null;
Bitmap bm = null;
try {
url = new URL(httpUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
InputStream in = url.openStream();
bm = BitmapFactory.decodeStream(in);
} catch (IOException e) {
e.printStackTrace();
}
return bm;
}
方法二:使用 BitmapFactory.decodeByteArray(data,0,data.length)
private Bitmap byteBitmap(String httpUrl) {
Bitmap bitmap = null;
try {
HttpURLConnection connection = (HttpURLConnection)(new URL(httpUrl)).openConnection();
connection.setDoInput(true);
connection.connect();
InputStream is = connection.getInputStream();
try {
byte[] data = readStream(is);
if(data != null){
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
public static byte[] readStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len=inStream.read(buffer)) != -1){
outStream.write(buffer, 0, len);
}
outStream.close();
inStream.close();
return outStream.toByteArray();
}