android开发----异步下载图片,并且进行缓存和显示图片

在Android应用中,为提升用户体验,通常会使用缓存机制来加速图片显示。本文提供了一个简单的实例,介绍了如何实现异步下载图片并缓存在SD卡上。当图片已缓存时,直接从缓存读取;否则,执行下载操作。代码包括异步类的实现,并附带Logcat输出以验证执行流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在android的网络应用中,下载图片和显示图片需要消耗大量的时间,通过应用缓存机制可以提高用户体验,下面就给出一个简单的实例。

代码思路:

   1.首先获取SDcard路径,在SDcard中新建文件夹作为图片缓存的地址,,利用hashmap保存url和对应的文件地址

   2.进行判断图片是否已经下载过,如果下载过则从缓存中获取并且显示在页面上,如果没有则执行下载

下面是代码,代码里面有详细的说明:

1.异步类


public class DownloadTask extends AsyncTask<String,Integer,Integer> {
    private String cachepath,urlString;
    private  File file;
    private ImageView imageView;

    private Map<String,String> cacheMap;

    public DownloadTask(String cachepath,File file,ImageView imageView,Map<String,String> cacheMap,String urlString) {
        this.cachepath = cachepath;
        this.urlString=urlString;
        this.file=file;
        this.imageView=imageView;
        this.cacheMap=cacheMap;
    }

    private URL url=null;
    @Override
    protected Integer doInBackground(String... params) {
        //获取url
        String urlString=params[0];
        try {
            url=new URL(urlString);
            //打开网络连接
            HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
            InputStream inputStream=httpURLConnection.getInputStream();
            //获取文件名称
            String filename=urlString.substring(urlString.lastIndexOf("/")+1);
            //实例化新的文件目录
            File dir=new File(cachepath);
            //判断文件目录是否存在
            if (!dir.exists()){
                //创建新目录
                dir.mkdir();
            }
            //创建新文件
            file=new File(cachepath+filename);
            file.createNewFile();
            OutputStream outputStream=new FileOutputStream(file);
            byte[] bytes=new byte[1024*4];
            //写文件
            while (inputStream.read(bytes)!=-1){
                outputStream.write(bytes);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return 1;
    }

    @Override
    protected void onPostExecute(Integer result) {
        if (result>0){
            //保存到缓存中,更新键值对
            cacheMap.put(urlString, file.getPath());
            Drawable drawable=Drawable.createFromPath(file.getPath());
            imageView.setImageDrawable(drawable);


        }
    }
}
主类:


public class MainActivity extends AppCompatActivity {
    private ImageView imageView;
    private EditText editText;
    private Button button;
    //新建url对象
    private URL url;
    //获取SDcard根目录
    private String sdCardpath= Environment.getExternalStorageDirectory()+"/";
    //设置缓存目录
    private String cachePath=sdCardpath+"picCaches/";

    private Map<String,String> cacheMap=new HashMap<String,String>();
    private File file;

    private String urlString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView= (ImageView) findViewById(R.id.imageview);
        editText= (EditText) findViewById(R.id.urltext);
        button= (Button) findViewById(R.id.send);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                urlString=editText.getText().toString();
                if (urlString!=null&&urlString.length()>0){
                    //判断是否以http开头
                    urlString=urlString.startsWith("http://")?urlString:"http://"+urlString;
                    //判断是否进行过缓存
                    if (cacheMap!=null&&cacheMap.containsKey(urlString))
                    {
                        //获取保存的地址
                        String cachefilePath=cacheMap.get(urlString).toString();
                        //验证该地址文档是否存在
                        if (FilePathExist(cachefilePath)){
                            Log.e("file","isexist");
                            //存在就显示缓存内容
                            Drawable drawable=Drawable.createFromPath(cachefilePath);
                            imageView.setImageDrawable(drawable);
                            Log.e("显示","执行缓存");

                        }else {
                            Log.e("download","执行下载");
                            //下载内容
                            downFile(urlString);
                        }

                    }else {
                        Log.e("download-------","执行下载");
                        downFile(urlString);

                    }


                }

            }
        });
    }
    //下载文件
    private void downFile(String urlString) {
        //开启异步任务
        new DownloadTask(cachePath,file,imageView,cacheMap,urlString).execute(urlString);

    }
    //判断文件路径是否存在

    private boolean FilePathExist(String cachefilepath) {

        File file=new File(cachefilepath);

        return  file.exists();

    }

}
下面是结果:


由于图片像素问题所以现实的不清楚这里就不多做说明了,下面是执行的logcat输出:


可以看到,当我第一次点击按钮时候,执行的是下载图片的操作,也就是

Log.e("download-------","执行下载");
downFile(urlString);
这个操作,然后我再次点击按钮时候,则跳出了执行缓存的操作,说明文件已经存在,我们直接加载到页面时就可以了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值