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

关联篇

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

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

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

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

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

基础配置

加入以下权限

    <uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

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;/*** @author MrLiu* @date 2021/3/12* desc*/
public class BannerInfo implements Serializable {/*** 图片地址*/private String picUrl;/*** type分类 1:图片 2:视屏*/private int type;/*** 无效的本地资源的状态* 0:非本地资源* 1:有效的本地资源*/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());/* 因为我针对不同场景保存图片的地方有所不同,所以做了渠道分配,常规使用的话直接存储固定地址即可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);}*/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 = "";//如果不需要分渠道做优化,则可固定一个路径/*if (source == 1) {path = Constant.LocalPath.BANNER_PATH;} else if (source == 2) {path = Constant.LocalPath.CERTIFICATE_PATH;} else {path = Constant.LocalPath.DEFAULT_PATH;}*/path = Environment.getExternalStorageDirectory().getPath() + "/default";//定义存储文件名String tmpFileName = System.currentTimeMillis() + ".mp4";//开始下载OkHttpUtils.get().url(picUrl).build().execute(new FileCallBack(path, tmpFileName) {@Overridepublic void onError(Call call, Exception e, int id) {LogTool.e("视频下载错误:" + e.getMessage());downAloneVideo(source, info);}@Overridepublic 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<BannerInfo> bannerList) {//检测本地数据库数据List<PictureEntity> localList = (List<PictureEntity>) 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) {@Overridepublic void onError(Call call, Exception e, int id) {LogTool.e("视频下载错误:" + e.getMessage());downAloneVideo(source, info);}@Overridepublic 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);

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

  1. Android进阶之路 - 批量下载、缓存图片

    在日常项目开发中,关于图片批量下载,数据缓存的相关功能比比皆是,这次也是去年在项目中需要在本地缓存商品数据,所以用到了批量下载的功能,特此记录 ~ 关联篇 Android进阶之路 - 批量下载.缓存图 ...

  2. Android进阶之路 - 解决部分手机拍照之后图片被旋转的问题

    这几天犯了一个错误,初期想着甩锅给后台的- 但还好及时发现了是自身的问题~ 关联文章 Android基础进阶 - 调用拍照.获取图片(基础) Android基础进阶 - 获取.调用相册内图片(基础) ...

  3. Android框架之路——Glide加载图片(结合RecyclerView、CardView)

    Android框架之路--Glide加载图片 一.简介: 在泰国举行的谷歌开发者论坛上,谷歌为我们介绍了一个名叫 Glide 的图片加载库,作者是bumptech.这个库被广泛的运用在google的开 ...

  4. aspx网页背景图片设置代码_python requests,BeautifulSoup批量下载360图片

    本代码演示通过python的requests,BeautifulSoup库批量下载360图片,并保存在本机的路径 代码如下: #BeautifulSoup库是网页爬虫解析库,主要用来对HTML源代码进 ...

  5. Android进阶之路 - 存、取、读 本地 Json 文件

    最近在开发中又开始加载一些本地的json数据源,回头看之前竟然没记录,赶紧记录一波 ~ 如何准备一个合格的json文件? AndoridStudio中如何存放json文件? 如何读取本地Json文件数 ...

  6. python爬虫实现批量下载百度图片

    今天和小伙伴们合作一个小项目,需要用到景点图片作为数据源,在百度上搜索了一些图片,感觉一个一个手动保存太过麻烦,于是想到用爬虫来下载图片. 本次代码用到了下列一些python模块,需要预先安装Beau ...

  7. Python实用案例,Python脚本,Python实现批量下载百度图片

    往期回顾 Python实现自动监测Github项目并打开网页 Python实现文件自动归类 Python实现帮你选择双色球号码 Python实现每日更换"必应图片"为"桌 ...

  8. python怎么批量下载图片_怎样批量下载在线图片?

    原标题:怎样批量下载在线图片? 大家早啊,我是云景,以前分享过很多关于批量下载图片的技巧,有使用插件程序的,有使用工具的. 之前也教过大家怎么使用F12开发者 今天给大家分享的是,使用Python来批 ...

  9. python批量下载必应图片

    梗概:我是个化验师,我们可是也要我们做PPT,医学知识往往繁多复杂,要是有比较好的照片配合文字,可以大大增加PPT的效果.必应这个网站可以搜索到比较有价值的医学图片,要是你输入一个医学名词,同样的搜索 ...

最新文章

  1. 查找点链表中倒数第k个数
  2. ASP.NET CORE 1.0 MVC API 文档用 SWASHBUCKLE SWAGGER实现
  3. java List及其实现类
  4. 块级元素与行级元素(内联元素)
  5. 普大喜奔 | Azure 免费送网站SSL证书啦!
  6. 集合拷贝通用方法、list<A> 转换成 list<B> (属性相同)
  7. html段落前的空格,HTML空格:空格前后
  8. HTTP和WebSocket协议(二)
  9. 软件设计师09-面向对象-图集
  10. [BZOJ3684]大朋友和多叉树
  11. 记一次oracle安装错误:INFO: //usr/lib64/libstdc++.so.5: undefined reference to `memcpy@GLIBC_2.14'...
  12. 【超分辨率】何凯明新作:Masked Autoencoders Are Scalable Vision Learners
  13. 配置Ubuntu软件源
  14. 【STM32技巧】使用STM32 HAL库的硬件I2C驱动RX8025T实时时钟芯片
  15. 网络层协议——ICMP协议
  16. 技术岗的职业规划_技术人员职业规划精选范文
  17. t6服务器的系统数据库不存在,用友T6软件出纳管理系统数据库质疑用任何方法无法恢复时解决方法-用友T6...
  18. 使用Hexo 在本地搭建博客(一)
  19. 伦斯勒理工大学计算机专业,伦斯勒理工学院计算机科学硕士排名第60(2020年TFE Times排名)...
  20. 好消息,Vue3官方文档出中文版的啦!

热门文章

  1. 中断系统的简单了解以及C51(STC89C52)单片机中断系统的详解
  2. VHDL 计数器实验看VHDL语言
  3. 淘宝开放平台TOP SDK调用对接淘宝或天猫
  4. Python数据分析前景如何
  5. 真正中文版攻略之出云战记零IZUMO0
  6. 驱动认知 驱动的编写
  7. dubbo启动报错 用法: appletviewer options url 这个是为什么
  8. java队列长度_Java实现固定长度队列
  9. XueTr (下载)系统辅助工具
  10. 数字中国城市巡礼之南通,公安的“达摩克利斯之剑”