public class ImageLoadAsyncTask extends AsyncTask
/**
* 定义一个图片的接口回调
*/
public interface ImageCallBack{
void callBitmap(Bitmap bitmap);
}
//定义变量记住调用者所传递进来的回调监听对象
private ImageCallBack imageCallBack;
//构造方法
public ImageLoadAsyncTask(ImageCallBack imageCallBack){
this.imageCallBack = imageCallBack;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if(bitmap != null){
//设置图片 回调回去
imageCallBack.callBitmap(bitmap);
}
}
@Override
protected Bitmap doInBackground(String... params) {
try {
String path = params[0];
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5*1000);
connection.setReadTimeout(5*1000);
//服务器响应
int code = connection.getResponseCode();
if(code == HttpURLConnection.HTTP_OK){//判断服务器是否连接成功并相应
//图片流
InputStream is = connection.getInputStream();
//将图片流转化成Bitmap位图,返回
return BitmapFactory.decodeStream(is);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private ImageView ivIcon;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ivIcon = (ImageView) findViewById(R.id.ivIcon);
}
public void btnLoadImage(View v){
loadImg("http://20.1.3.46:8080/tomcat.png");
}
/**
* 加载图片
* @param url 图片地址
*/
private void loadImg(String url){
ImageLoadAsyncTask imageLoadAsyncTask = new ImageLoadAsyncTask(new ImageLoadAsyncTask.ImageCallBack() {
@Override
public void callBitmap(Bitmap bitmap) {
if(bitmap != null){
ivIcon.setImageBitmap(bitmap);
}
}
});
//执行图片请求
imageLoadAsyncTask.execute(url);
}
这就可以加载出来特别简单的图片了。