package com.example.mydouban;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
public class LoadImageAsynTask extends AsyncTask<String, Void, Bitmap>{
LoadImageAsynTaskCallBack loadImageAsynTaskCallBack;
public LoadImageAsynTask(LoadImageAsynTaskCallBack loadImageAsynTaskCallBack){
this.loadImageAsynTaskCallBack=loadImageAsynTaskCallBack;
}
//设置回调接口
public interface LoadImageAsynTaskCallBack{
public void beforeLoadImage();
public void afterLoadImage();
}
/*
* 异步任务执行之前调用
*/
@Override
protected void onPreExecute() {
//具体执行什么操作LoadImageAsynTask不知道
//让调用LoadImageAsynTask的人去实现
loadImageAsynTaskCallBack.beforeLoadImage();
super.onPreExecute();
}
/*
* 异步任务执行之后调用
*/
@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
loadImageAsynTaskCallBack.afterLoadImage();
super.onPostExecute(result);
}
/*
* 后台子线程运行的异步任务
*/
@Override
protected Bitmap doInBackground(String... params) {
try {
String path=params[0];
URL url=new URL(path);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
InputStream is=conn.getInputStream();
return BitmapFactory.decodeStream(is);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
// 调用这个异步任务并且sd卡缓存图片
//加入两个sd卡的权限 WRITE_EXTERNAL_STORAGE MOUNT_NUMOUNT_FILESYSTEM
//获取图片的名称
String iconurl=url;
String iconName=iconurl.substring(iconurl.lastIndexOf("/")+1, iconurl.length());
File file=new File("/sdcard/"+iconName);
if(file.exists()){
iv_icon.setImageURI(Uri.fromFile(file));
}else{
LoadImageAsynTask task=new LoadImageAsynTask(new LoadImageAsynTaskCallBack() {
@Override
public void beforeLoadImage() {
// TODO Auto-generated method stub
iv_icon.setImageResource();
}
@Override
public void afterLoadImage(Bitmap bitmap) {
// TODO Auto-generated method stub
if(bitmap!=null){
iv_icon.setImageBitmap(bitmap);
//把图片保存到sd卡上
File file=new File("/sdcard/"+iconName);
FileOutputStream stream=new FileOutputStream(file);
bitmap.compress(CompressFormat.JPEG, 100, stream);
}
else{
iv_icon.setImageResource();
}
}
});
task.execute(url);
}
}
异步任务下载网络图片
最新推荐文章于 2021-05-12 00:16:18 发布