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

相关文章

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

Android ClassLoader加载机制详解

《AndroidClassLoader加载机制详解》Android的ClassLoader负责加载.dex文件,基于双亲委派模型,支持热修复和插件化,需注意类冲突、内存泄漏和兼容性问题,本文给大家介... 目录一、ClassLoader概述1.1 类加载的基本概念1.2 android与Java Class

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Golang如何对cron进行二次封装实现指定时间执行定时任务

《Golang如何对cron进行二次封装实现指定时间执行定时任务》:本文主要介绍Golang如何对cron进行二次封装实现指定时间执行定时任务问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录背景cron库下载代码示例【1】结构体定义【2】定时任务开启【3】使用示例【4】控制台输出总结背景

SpringBoot开发中十大常见陷阱深度解析与避坑指南

《SpringBoot开发中十大常见陷阱深度解析与避坑指南》在SpringBoot的开发过程中,即使是经验丰富的开发者也难免会遇到各种棘手的问题,本文将针对SpringBoot开发中十大常见的“坑... 目录引言一、配置总出错?是不是同时用了.properties和.yml?二、换个位置配置就失效?搞清楚加

使用Python进行GRPC和Dubbo协议的高级测试

《使用Python进行GRPC和Dubbo协议的高级测试》GRPC(GoogleRemoteProcedureCall)是一种高性能、开源的远程过程调用(RPC)框架,Dubbo是一种高性能的分布式服... 目录01 GRPC测试安装gRPC编写.proto文件实现服务02 Dubbo测试1. 安装Dubb

Android DataBinding 与 MVVM使用详解

《AndroidDataBinding与MVVM使用详解》本文介绍AndroidDataBinding库,其通过绑定UI组件与数据源实现自动更新,支持双向绑定和逻辑运算,减少模板代码,结合MV... 目录一、DataBinding 核心概念二、配置与基础使用1. 启用 DataBinding 2. 基础布局

Python中对FFmpeg封装开发库FFmpy详解

《Python中对FFmpeg封装开发库FFmpy详解》:本文主要介绍Python中对FFmpeg封装开发库FFmpy,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录一、FFmpy简介与安装1.1 FFmpy概述1.2 安装方法二、FFmpy核心类与方法2.1 FF

Android ViewBinding使用流程

《AndroidViewBinding使用流程》AndroidViewBinding是Jetpack组件,替代findViewById,提供类型安全、空安全和编译时检查,代码简洁且性能优化,相比Da... 目录一、核心概念二、ViewBinding优点三、使用流程1. 启用 ViewBinding (模块级

HTML5实现的移动端购物车自动结算功能示例代码

《HTML5实现的移动端购物车自动结算功能示例代码》本文介绍HTML5实现移动端购物车自动结算,通过WebStorage、事件监听、DOM操作等技术,确保实时更新与数据同步,优化性能及无障碍性,提升用... 目录1. 移动端购物车自动结算概述2. 数据存储与状态保存机制2.1 浏览器端的数据存储方式2.1.