android移动开发-单文件下载-基于官方DownLoadManager进行

2023-11-08 10:18

本文主要是介绍android移动开发-单文件下载-基于官方DownLoadManager进行,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

代码取自Demo ,实现单文件下载并弹出打开方式,由于采用意图Intent方式,所以很多高度定制的Rom就可能进入异常了,我在后期会整合网络资源,整理出一个新的方案!

1-工具类,简单看一下 ,看懂了就好

/*** Created by Administrator on 2016/11/23.*/public class DownLoadMng {/*** 得到一个经过基本初始化的请求实例** @param url* @return*/
public static DownloadManager.Request getRequest(String url) {DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));//设置在什么网络情况下进行下载request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);//设置通知栏标题request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);request.setTitle("通知栏显示");request.setDescription("通知栏下拉的条目上显示");request.setAllowedOverRoaming(false);return request;
}/*** 这个好用** @param activity activity引用,用于跳intent* @param path     文件路径*/
public static void openFile2(Activity activity, String path) {File f = new File(path);Intent intent = new Intent();intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.setAction(android.content.Intent.ACTION_VIEW);/* 调用getMIMEType()来取得MimeType */String type = getMIMEType(f);/* 设置intent的file与MimeType */intent.setDataAndType(Uri.fromFile(f), type);try {activity.startActivity(intent);} catch (ActivityNotFoundException e) {Toast.makeText(context, "附件无法打开,请下载相关软件!", 500).show();}
}/* 判断文件MimeType的method */
private static String getMIMEType(File f) {String type = "";String fName = f.getName();/* 取得扩展名 */String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();/* 依扩展名的类型决定MimeType */if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") ||end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {type = "audio";} else if (end.equals("3gp") || end.equals("mp4")) {type = "video";} else if (end.equals("jpg") || end.equals("gif") || end.equals("png") ||end.equals("jpeg") || end.equals("bmp")) {type = "image";} else if (end.equals("apk")) {/* android.permission.INSTALL_PACKAGES */type = "application/vnd.android.package-archive";} else if (end.equals("xls")) {type = "application/vnd.ms-excel";} else if (end.equals("word") || end.contains("doc")) {type = "application/msword";}/*如果无法直接打开,就跳出软件列表给用户选择 */if (end.equals("apk")) {} else {type += "/*";}return type;
}/*** 这个有隐藏bug  不用了   并且下面的方法全引用自此方法  故不用** @param filePath* @return*/
@Deprecated
public static Intent openFile(String filePath) {File file = new File(filePath);if (!file.exists()) return null;/* 取得扩展名 */String end = file.getName().substring(file.getName().lastIndexOf(".") + 1, file.getName().length()).toLowerCase();/* 依扩展名的类型决定MimeType */if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") ||end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {return getAudioFileIntent(filePath);} else if (end.equals("3gp") || end.equals("mp4")) {return getAudioFileIntent(filePath);} else if (end.equals("jpg") || end.equals("gif") || end.equals("png") ||end.equals("jpeg") || end.equals("bmp")) {return getImageFileIntent(filePath);} else if (end.equals("apk")) {return getApkFileIntent(filePath);} else if (end.equals("ppt")) {return getPptFileIntent(filePath);} else if (end.equals("xls")) {return getExcelFileIntent(filePath);} else if (end.equals("doc")) {return getWordFileIntent(filePath);} else if (end.equals("pdf")) {return getPdfFileIntent(filePath);} else if (end.equals("chm")) {return getChmFileIntent(filePath);} else if (end.equals("txt")) {return getTextFileIntent(filePath, false);} else {return getAllIntent(filePath);}
}//Android获取一个用于打开APK文件的intent
@Deprecated
public static Intent getAllIntent(String param) {Intent intent = new Intent();intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.setAction(android.content.Intent.ACTION_VIEW);Uri uri = Uri.fromFile(new File(param));intent.setDataAndType(uri, "*/*");return intent;
}//Android获取一个用于打开APK文件的intent
public static Intent getApkFileIntent(String param) {Intent intent = new Intent();intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.setAction(android.content.Intent.ACTION_VIEW);Uri uri = Uri.fromFile(new File(param));intent.setDataAndType(uri, "application/vnd.android.package-archive");return intent;
}//Android获取一个用于打开VIDEO文件的intent
public static Intent getVideoFileIntent(String param) {Intent intent = new Intent("android.intent.action.VIEW");intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);intent.putExtra("oneshot", 0);intent.putExtra("configchange", 0);Uri uri = Uri.fromFile(new File(param));intent.setDataAndType(uri, "video/*");return intent;
}//Android获取一个用于打开AUDIO文件的intent
public static Intent getAudioFileIntent(String param) {Intent intent = new Intent("android.intent.action.VIEW");intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);intent.putExtra("oneshot", 0);intent.putExtra("configchange", 0);Uri uri = Uri.fromFile(new File(param));intent.setDataAndType(uri, "audio/*");return intent;
}//Android获取一个用于打开Html文件的intent
public static Intent getHtmlFileIntent(String param) {Uri uri = Uri.parse(param).buildUpon().encodedAuthority("com.android.htmlfileprovider").scheme("content").encodedPath(param).build();Intent intent = new Intent("android.intent.action.VIEW");intent.setDataAndType(uri, "text/html");return intent;
}//Android获取一个用于打开图片文件的intent
public static Intent getImageFileIntent(String param) {Intent intent = new Intent("android.intent.action.VIEW");intent.addCategory("android.intent.category.DEFAULT");intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);Uri uri = Uri.fromFile(new File(param));intent.setDataAndType(uri, "image/*");return intent;
}//Android获取一个用于打开PPT文件的intent
public static Intent getPptFileIntent(String param) {Intent intent = new Intent("android.intent.action.VIEW");intent.addCategory("android.intent.category.DEFAULT");intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);Uri uri = Uri.fromFile(new File(param));intent.setDataAndType(uri, "application/vnd.ms-powerpoint");return intent;
}//Android获取一个用于打开Excel文件的intent
public static Intent getExcelFileIntent(String param) {Intent intent = new Intent("android.intent.action.VIEW");intent.addCategory("android.intent.category.DEFAULT");intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);Uri uri = Uri.fromFile(new File(param));intent.setDataAndType(uri, "application/vnd.ms-excel");return intent;
}//Android获取一个用于打开Word文件的intent
public static Intent getWordFileIntent(String param) {Intent intent = new Intent("android.intent.action.VIEW");intent.addCategory("android.intent.category.DEFAULT");intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);Uri uri = Uri.fromFile(new File(param));intent.setDataAndType(uri, "application/msword");return intent;
}//Android获取一个用于打开CHM文件的intent
public static Intent getChmFileIntent(String param) {Intent intent = new Intent("android.intent.action.VIEW");intent.addCategory("android.intent.category.DEFAULT");intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);Uri uri = Uri.fromFile(new File(param));intent.setDataAndType(uri, "application/x-chm");return intent;
}//Android获取一个用于打开文本文件的intent
public static Intent getTextFileIntent(String param, boolean paramBoolean) {Intent intent = new Intent("android.intent.action.VIEW");intent.addCategory("android.intent.category.DEFAULT");intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);if (paramBoolean) {Uri uri1 = Uri.parse(param);intent.setDataAndType(uri1, "text/plain");} else {Uri uri2 = Uri.fromFile(new File(param));intent.setDataAndType(uri2, "text/plain");}return intent;
}//Android获取一个用于打开PDF文件的intent
public static Intent getPdfFileIntent(String param) {Intent intent = new Intent("android.intent.action.VIEW");intent.addCategory("android.intent.category.DEFAULT");intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);Uri uri = Uri.fromFile(new File(param));intent.setDataAndType(uri, "application/pdf");return intent;
}
}

2、开始下载

        private void downLoad(){
DownloadManager.Request request = DownLoadMng.getRequest(url);//设置文件存放目录path = "/yangguang";//Environment.getExternalStorageDirectory().getAbsolutePath()isFolderExist(path);//文件夹判空filename = accessmodel.getData().getFile_list().get(position).getTitle();request.setDestinationInExternalPublicDir(path, filename);absolutePath = path + "/" + filename;downManager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);id = downManager.enqueue(request);getActivity().registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));// 监听下载状态}private BroadcastReceiver receiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {//这里可以取得下载的id,这样就可以知道哪个文件下载完成了。适用与多个下载任务的监听Log.v("intent", "" + intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0));queryDownloadStatus();}
};private void queryDownloadStatus() {DownloadManager.Query query = new DownloadManager.Query();query.setFilterById(id);Cursor c = downManager.query(query);if (c.moveToFirst()) {int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));switch (status) {case DownloadManager.STATUS_PAUSED:Log.v("debug", "STATUS_PAUSED");case DownloadManager.STATUS_PENDING:Log.v("debug", "STATUS_PENDING");case DownloadManager.STATUS_RUNNING://正在下载,不做任何事情Log.v("debug", "下载中");break;case DownloadManager.STATUS_SUCCESSFUL://完成showToast("下载完成");try {DownLoadMng.openFile2(getActivity(), absolutePath);} catch (Exception e) {e.printStackTrace();DebugLogUtil.getInstance().Error("打开失败~" + e);}break;case DownloadManager.STATUS_FAILED://清除已下载的内容,重新下载showToast("下载失败");
//                    Log.v("debug", "STATUS_FAILED");
//                    downManager.remove(id);
//                    id.edit().clear().commit();break;}}
}

这篇关于android移动开发-单文件下载-基于官方DownLoadManager进行的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/369164

相关文章

这15个Vue指令,让你的项目开发爽到爆

1. V-Hotkey 仓库地址: github.com/Dafrok/v-ho… Demo: 戳这里 https://dafrok.github.io/v-hotkey 安装: npm install --save v-hotkey 这个指令可以给组件绑定一个或多个快捷键。你想要通过按下 Escape 键后隐藏某个组件,按住 Control 和回车键再显示它吗?小菜一碟: <template

Hadoop企业开发案例调优场景

需求 (1)需求:从1G数据中,统计每个单词出现次数。服务器3台,每台配置4G内存,4核CPU,4线程。 (2)需求分析: 1G / 128m = 8个MapTask;1个ReduceTask;1个mrAppMaster 平均每个节点运行10个 / 3台 ≈ 3个任务(4    3    3) HDFS参数调优 (1)修改:hadoop-env.sh export HDFS_NAMENOD

嵌入式QT开发:构建高效智能的嵌入式系统

摘要: 本文深入探讨了嵌入式 QT 相关的各个方面。从 QT 框架的基础架构和核心概念出发,详细阐述了其在嵌入式环境中的优势与特点。文中分析了嵌入式 QT 的开发环境搭建过程,包括交叉编译工具链的配置等关键步骤。进一步探讨了嵌入式 QT 的界面设计与开发,涵盖了从基本控件的使用到复杂界面布局的构建。同时也深入研究了信号与槽机制在嵌入式系统中的应用,以及嵌入式 QT 与硬件设备的交互,包括输入输出设

OpenHarmony鸿蒙开发( Beta5.0)无感配网详解

1、简介 无感配网是指在设备联网过程中无需输入热点相关账号信息,即可快速实现设备配网,是一种兼顾高效性、可靠性和安全性的配网方式。 2、配网原理 2.1 通信原理 手机和智能设备之间的信息传递,利用特有的NAN协议实现。利用手机和智能设备之间的WiFi 感知订阅、发布能力,实现了数字管家应用和设备之间的发现。在完成设备间的认证和响应后,即可发送相关配网数据。同时还支持与常规Sof

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

常用的jdk下载地址

jdk下载地址 安装方式可以看之前的博客: mac安装jdk oracle 版本:https://www.oracle.com/java/technologies/downloads/ Eclipse Temurin版本:https://adoptium.net/zh-CN/temurin/releases/ 阿里版本: github:https://github.com/

活用c4d官方开发文档查询代码

当你问AI助手比如豆包,如何用python禁止掉xpresso标签时候,它会提示到 这时候要用到两个东西。https://developers.maxon.net/论坛搜索和开发文档 比如这里我就在官方找到正确的id描述 然后我就把参数标签换过来

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

Android平台播放RTSP流的几种方案探究(VLC VS ExoPlayer VS SmartPlayer)

技术背景 好多开发者需要遴选Android平台RTSP直播播放器的时候,不知道如何选的好,本文针对常用的方案,做个大概的说明: 1. 使用VLC for Android VLC Media Player(VLC多媒体播放器),最初命名为VideoLAN客户端,是VideoLAN品牌产品,是VideoLAN计划的多媒体播放器。它支持众多音频与视频解码器及文件格式,并支持DVD影音光盘,VCD影

业务中14个需要进行A/B测试的时刻[信息图]

在本指南中,我们将全面了解有关 A/B测试 的所有内容。 我们将介绍不同类型的A/B测试,如何有效地规划和启动测试,如何评估测试是否成功,您应该关注哪些指标,多年来我们发现的常见错误等等。 什么是A/B测试? A/B测试(有时称为“分割测试”)是一种实验类型,其中您创建两种或多种内容变体——如登录页面、电子邮件或广告——并将它们显示给不同的受众群体,以查看哪一种效果最好。 本质上,A/B测