package com.wzh.csdn.util;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by wzh on 2015/8/18.
*/
public class GetBitmapUtil {
public static void getBitmapByUrl(final String address,final callBackListener listener){
new AsyncTask<Void,Void,Bitmap>(){
@Override
protected Bitmap doInBackground(Void... params) {
//方式1:
Bitmap bm = null ;
try {
URL url = new URL(address) ;
InputStream is = url.openStream() ;
bm = BitmapFactory.decodeStream(is) ;
} catch (IOException e) {
e.printStackTrace();
}
return bm;
//方式2:
/*
Bitmap bm = null ;
HttpURLConnection hc = null ;
try {
URL url = new URL(address) ;
hc = (HttpURLConnection)url.openConnection() ;
hc.setRequestMethod("GET");
hc.connect();
if(hc.getResponseCode() == 200){
InputStream is = hc.getInputStream() ;
bm = BitmapFactory.decodeStream(is) ;
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(hc != null){
hc.disconnect();
}
}
return bm;
* */
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if(bitmap != null){
listener.onSuccess(bitmap);
}else{
listener.onFail();
}
super.onPostExecute(bitmap);
}
}.execute() ;
}
public static interface
callBackListener{
void onSuccess(Bitmap bm) ;
void onFail() ;
}
}
稍加改造就可以获取图片等资源
package com.wzh.csdn.util;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by wzh on 2015/8/18.
*/
public class GetBitmapUtil {
public static void getBitmapByUrl(final String address,final callBackListener listener){
new AsyncTask<Void,Void,Bitmap>(){
@Override
protected Bitmap doInBackground(Void... params) {
//方式1:
Bitmap bm = null ;
try {
URL url = new URL(address) ;
InputStream is = url.openStream() ;
bm = BitmapFactory.decodeStream(is) ;
} catch (IOException e) {
e.printStackTrace();
}
return bm;
//方式2:
/*
Bitmap bm = null ;
HttpURLConnection hc = null ;
try {
URL url = new URL(address) ;
hc = (HttpURLConnection)url.openConnection() ;
hc.setRequestMethod("GET");
hc.connect();
if(hc.getResponseCode() == 200){
InputStream is = hc.getInputStream() ;
bm = BitmapFactory.decodeStream(is) ;
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(hc != null){
hc.disconnect();
}
}
return bm;
* */
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if(bitmap != null){
listener.onSuccess(bitmap);
}else{
listener.onFail();
}
super.onPostExecute(bitmap);
}
}.execute() ;
}
public static interface
callBackListener{
void onSuccess(Bitmap bm) ;
void onFail() ;
}
}