栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Android进阶之路 - 批量下载、缓存图片、视频

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android进阶之路 - 批量下载、缓存图片、视频

之前已经记录过,批量下载图片和缓存本地的方式,此篇主要记录批量下载图片、视频,同时缓存在本地的功能实现

关联篇

  • Android进阶之路 - 批量下载、缓存图片
  • Android进阶之路 - 批量下载、缓存图片、视频

在此之前,我记录过一篇 主讲 - 批量下载、缓存图片,此篇可以作为上篇的进阶扩展,优化了调用场景和使用方式~

        • 基础配置
        • 图片下载
        • 视频下载
        • 完整封装
        • 使用方式

关于实现批量下载、缓存功能,主要使用了以下几方面的知识

  • 通过Glide下载图片
  • 通过okhttputils下载视频
  • greenDao数据库存储
基础配置

加入以下权限

    
    
    

build.gradle(app)

	//okHttpUtils网络框架
    implementation 'com.squareup.okhttp3:okhttp:3.11.0'
    implementation 'com.squareup.okio:okio:1.15.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
 	//glide图片框架
    implementation 'com.github.bumptech.glide:glide:4.3.1'
    annotationProcessor('com.github.bumptech.glide:compiler:4.3.1')
    implementation 'com.github.bumptech.glide:okhttp3-integration:4.3.1'
    //greenDao数据库框架
    implementation 'org.greenrobot:greendao:3.3.0'
    implementation 'org.greenrobot:greendao-generator:3.3.0'

BannerInfo

在下方code中用到的bean,用于区分下载类型、地址、存储状态

package com.nk.machine.shop.model;

import java.io.Serializable;


public class BannerInfo implements Serializable {
    
    private String picUrl;

    
    private int type;

    
    private int validLocalState = 0;

    public int getValidLocalState() {
        return validLocalState;
    }

    public void setValidLocalState(int validLocalState) {
        this.validLocalState = validLocalState;
    }
    
    public String getPicUrl() {
        return picUrl;
    }

    public void setPicUrl(String picUrl) {
        this.picUrl = picUrl;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }
}

图片下载
    
    public void downAloneImg(int source, BannerInfo info) {
        LogTool.e("提示:开始下载图片");
        String picUrl = info.getPicUrl();
        new Thread(() -> {
            File file = GlideTool.downImageFile(NkApplication.getAppContext(), picUrl);
            Bitmap bitmap = BitmapFactory.decodeFile(file.toString());
           
            
            saveAloneImg(info, bitmap, Environment.getExternalStorageDirectory().getPath() + "/default");
        }).start();
    }

    
    public void saveAloneImg(BannerInfo info, Bitmap bitmap, String path) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        try {
            String tmpImgPath = path + "/" + System.currentTimeMillis() + ".png";
            FileOutputStream fileOutputStream = new FileOutputStream(tmpImgPath);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
            fileOutputStream.close();

            int type = info.getType();
            String picUrl = info.getPicUrl();
            int interval = info.getInterval();
            LogTool.e("图片保存成功,tmpImgPath=" + tmpImgPath);
            DaoStrategy.getInstance(new LyPicture(1, interval, type, picUrl, tmpImgPath)).insert();
        } catch (Exception e) {
            LogTool.e(e.getMessage());
        }
    }
视频下载
    
    public void downAloneVideo(int source, BannerInfo info) {
        String picUrl = info.getPicUrl();
        LogTool.e("提示:开始下载视频"+picUrl));
        //定义存储路径
        String path = "";
        //如果不需要分渠道做优化,则可固定一个路径
        
        path = Environment.getExternalStorageDirectory().getPath() + "/default";
        //定义存储文件名
        String tmpFileName = System.currentTimeMillis() + ".mp4";
        //开始下载
        OkHttpUtils.get()
                .url(picUrl)
                .build()
                .execute(new FileCallBack(path, tmpFileName) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        LogTool.e("视频下载错误:" + e.getMessage());
                        downAloneVideo(source, info);
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        LogTool.e("视频下载成功"+response.getAbsolutePath());
                        //将数据保存到数据库中
                        DaoStrategy.getInstance(new LyPicture(1, interval, info.getType(), picUrl, response.getAbsolutePath())).insert();
                    }
                });
完整封装
public class DownLoadUtil{
 	
    public static synchronized void downVideoImg(List bannerList) {
        //检测本地数据库数据
        List localList = (List) DaoStrategy.getInstance(new LyPicture()).queryConditionList(1);
        for (int i = 0; i < bannerList.size(); i++) {
            BannerInfo info = bannerList.get(i);
            //检测本地数据库资源,查询是否存在已下载的资源,减少重复下载,提升效率(如不需要可删除)
            if (localList.size() >= 1) {
                for (int j = 0; j < localList.size(); j++) {
                    if (info.getPicUrl().equals(info.getPicUrl())) {
                        LogTool.e("提示:本地已有该资源");
                        return;
                    }
                }
            }
			//必有:主要判断是下载图片还是视频
            if (info.getType() == 2) {
                downAloneVideo(1, bannerList.get(i));
            } else {
                downAloneImg(1, bannerList.get(i));
            }
        }
    }

    
    public void downAloneImg(int source, BannerInfo info) {
        LogTool.e("提示:开始下载图片");
        String picUrl = info.getPicUrl();
        new Thread(() -> {
            File file = GlideTool.downImageFile(NkApplication.getAppContext(), picUrl);
            Bitmap bitmap = BitmapFactory.decodeFile(file.toString());
            if (source == 1) {
                saveAloneImg(info, bitmap, Constant.LocalPath.BANNER_PATH);
            } else if (source == 2) {
                saveAloneImg(info, bitmap, Constant.LocalPath.CERTIFICATE_PATH);
            } else {
                saveAloneImg(info, bitmap, Constant.LocalPath.DEFAULT_PATH);
            }
        }).start();
    }

    
    public void saveAloneImg(BannerInfo info, Bitmap bitmap, String path) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        try {
            String tmpImgPath = path + "/" + System.currentTimeMillis() + ".png";
            FileOutputStream fileOutputStream = new FileOutputStream(tmpImgPath);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
            fileOutputStream.close();

            int type = info.getType();
            String picUrl = info.getPicUrl();
            int interval = info.getInterval();
            LogTool.e("图片保存成功,tmpImgPath=" + tmpImgPath);
            DaoStrategy.getInstance(new LyPicture(1, interval, type, picUrl, tmpImgPath)).insert();
        } catch (Exception e) {
            LogTool.e(e.getMessage());
        }
    }

    
    public void downAloneVideo(int source, BannerInfo info) {
        LogTool.e("提示:开始下载视频"+info.getPicUrl());
        String picUrl = info.getPicUrl();
        int interval = info.getInterval();
        String path = "";
        if (source == 1) {
            path = Constant.LocalPath.BANNER_PATH;
        } else if (source == 2) {
            path = Constant.LocalPath.CERTIFICATE_PATH;
        } else {
            path = Constant.LocalPath.DEFAULT_PATH;
        }
        String tmpFileName = System.currentTimeMillis() + ".mp4";
        OkHttpUtils.get()
                .url(picUrl)
                .build()
                .execute(new FileCallBack(path, tmpFileName) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        LogTool.e("视频下载错误:" + e.getMessage());
                        downAloneVideo(source, info);
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        LogTool.e("视频下载成功"+response.getAbsolutePath());
                        DaoStrategy.getInstance(new LyPicture(1, interval, info.getType(), picUrl, response.getAbsolutePath())).insert();
                    }
                });
    }
使用方式

使用简单,无需关注内部实现,同时实现了单一原则,统一了下载出口

在需要下载视频、图片的地方直接调用以下代码即可

   //bannerList为需要下载的图片和视频
   DownLoadUtil.downVideoImg(bannerList);
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/631082.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号