android 使用download Manager实现应用下载安装

2024-06-04 21:38

本文主要是介绍android 使用download Manager实现应用下载安装,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

        android 2.3中引入了download manager ,作为一个service来优化长时间下载操作处理。download manager通过处理http 连接、监听连续的变化和系统重新启动来确保每一次下载都能成功完成。

最好大多数场景下都使用download manager,特别是在一个下载可能会在多个用户回话之间在后台继续进行的地方或者在某个下载的完成非常重要的时候。

1、用到的权限

 <uses-permission android:name="android.permission.INTERNET"></uses-permission><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION"/>
2、实现现在文件,需要创建一个新的DownloadManager.Request,指定要下载的文件的uri

/*** 下载文件*/private void Download(){String serviceString = Context.DOWNLOAD_SERVICE;downloadManager = (DownloadManager)getSystemService(serviceString);Uri uri = Uri.parse("http://dingphone.ufile.ucloud.com.cn/apk/guanwang/time2plato.apk");//Uri uri = Uri.parse("http://omoml61n3.bkt.clouddn.com/Android%E5%BA%94%E7%94%A8%E6%BA%90%E7%A0%81%E9%9F%B3%E4%B9%90%E5%AE%9E%E6%97%B6%E8%B7%B3%E5%8A%A8%E9%A2%91%E8%B0%B1%E6%98%BE%E7%A4%BA.rar");DownloadManager.Request request = new DownloadManager.Request(uri);//设置下载路径request.setDestinationInExternalPublicDir("download", "time2plato.apk");request.setTitle("标题");request.setDescription("文件下载名设置");//wifi才下载request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);request.setMimeType("application/vnd.android.package-archive");id = downloadManager.enqueue(request);}
3、想要在文件下载完成后对文件进行操作需要注册一个Receiver来接收 ACTION_DOWNLOAD_COMPLETE广播

IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);receiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {Receive(intent);openFile(new File("/sdcard/Download/time2plato.apk"));}else if (intent.getAction().equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)){Toast.makeText(getApplication(),"正在下载",Toast.LENGTH_SHORT).show();}}};registerReceiver(receiver,filter);
4、下载完成后打开安装功能实现

/*** 跳转更新文件* @param file*/private void openFile(File file) {// TODO Auto-generated method stubIntent intent = new Intent();intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.setAction(android.content.Intent.ACTION_VIEW);intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");startActivity(intent);}
5、取消和删除下载,romove方法可以接受下载id作为参数选择,并且允许指定一个或多个要取消的下载。downloadManager.remove(id1,id2,id3);

downloadManager.remove(id);
6、获取下载文件名和路径实现

 /*** 获取文件下载路径和uri* @param intent*/private void Receive(Intent intent){long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,-1);DownloadManager.Query mydown = new DownloadManager.Query();mydown.setFilterById(reference);Cursor myDownload = downloadManager.query(mydown);if (myDownload.moveToFirst()){int fileNameIdx = myDownload.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);int fileUriIdx = myDownload.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);String fileName = myDownload.getString(fileNameIdx);String fileUri = myDownload.getString(fileUriIdx);tvDown.setText("filename="+fileName+" fileUri="+fileUri);}myDownload.close();}

7、获取当前下载状态

/*** 获取当前状态*/private void queryDownloadStatus() {DownloadManager.Query query = new DownloadManager.Query();query.setFilterById(id);Cursor c = downloadManager.query(query);if(c.moveToFirst()) {int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));switch(status) {case DownloadManager.STATUS_PAUSED:Log.e("down", "STATUS_PAUSED");case DownloadManager.STATUS_PENDING:Log.e("down", "STATUS_PENDING");case DownloadManager.STATUS_RUNNING://正在下载,不做任何事情Log.e("down", "STATUS_RUNNING");break;case DownloadManager.STATUS_SUCCESSFUL://完成Log.e("down", "下载完成");break;case DownloadManager.STATUS_FAILED://清除已下载的内容,重新下载Log.e("down", "STATUS_FAILED");break;}}}

8、取消注册
 @Overrideprotected void onDestroy() {if (receiver!=null) {unregisterReceiver(receiver);receiver = null;}super.onDestroy();}
最后完整代码

package com.example.apple.downloadmanager;import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;import java.io.File;public class MainActivity extends AppCompatActivity {private Button btnDown;private DownloadManager downloadManager;private BroadcastReceiver receiver;private TextView tvDown;private Button btnRemove;private long id;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();}private void initView() {tvDown = (TextView)findViewById(R.id.tv_down);btnDown = (Button)findViewById(R.id.btn_down);btnDown.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Download();//intoDownloadManager();}});IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);receiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {Receive(intent);openFile(new File("/sdcard/Download/time2plato.apk"));}else if (intent.getAction().equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)){Toast.makeText(getApplication(),"正在下载",Toast.LENGTH_SHORT).show();}}};registerReceiver(receiver,filter);btnRemove = (Button)findViewById(R.id.btn_remove);btnRemove.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// downloadManager.remove(id);queryDownloadStatus();}});}/*** 获取当前状态*/private void queryDownloadStatus() {DownloadManager.Query query = new DownloadManager.Query();query.setFilterById(id);Cursor c = downloadManager.query(query);if(c.moveToFirst()) {int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));switch(status) {case DownloadManager.STATUS_PAUSED:Log.e("down", "STATUS_PAUSED");case DownloadManager.STATUS_PENDING:Log.e("down", "STATUS_PENDING");case DownloadManager.STATUS_RUNNING://正在下载,不做任何事情Log.e("down", "STATUS_RUNNING");break;case DownloadManager.STATUS_SUCCESSFUL://完成Log.e("down", "下载完成");break;case DownloadManager.STATUS_FAILED://清除已下载的内容,重新下载Log.e("down", "STATUS_FAILED");break;}}}/*** 跳转更新文件* @param file*/private void openFile(File file) {// TODO Auto-generated method stubIntent intent = new Intent();intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.setAction(android.content.Intent.ACTION_VIEW);intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");startActivity(intent);}/*** 下载文件*/private void Download(){String serviceString = Context.DOWNLOAD_SERVICE;downloadManager = (DownloadManager)getSystemService(serviceString);Uri uri = Uri.parse("http://dingphone.ufile.ucloud.com.cn/apk/guanwang/time2plato.apk");//Uri uri = Uri.parse("http://omoml61n3.bkt.clouddn.com/Android%E5%BA%94%E7%94%A8%E6%BA%90%E7%A0%81%E9%9F%B3%E4%B9%90%E5%AE%9E%E6%97%B6%E8%B7%B3%E5%8A%A8%E9%A2%91%E8%B0%B1%E6%98%BE%E7%A4%BA.rar");DownloadManager.Request request = new DownloadManager.Request(uri);//设置下载路径request.setDestinationInExternalPublicDir("download", "time2plato.apk");request.setTitle("标题");request.setDescription("文件下载名设置");//wifi才下载request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);request.setMimeType("application/vnd.android.package-archive");id = downloadManager.enqueue(request);}/*** 获取文件下载路径和uri* @param intent*/private void Receive(Intent intent){long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,-1);DownloadManager.Query mydown = new DownloadManager.Query();mydown.setFilterById(reference);Cursor myDownload = downloadManager.query(mydown);if (myDownload.moveToFirst()){int fileNameIdx = myDownload.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);int fileUriIdx = myDownload.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);String fileName = myDownload.getString(fileNameIdx);String fileUri = myDownload.getString(fileUriIdx);tvDown.setText("filename="+fileName+" fileUri="+fileUri);}myDownload.close();}@Overrideprotected void onDestroy() {if (receiver!=null) {unregisterReceiver(receiver);receiver = null;}super.onDestroy();}
}
代码下载: http://download.csdn.net/detail/u011324501/9812299






这篇关于android 使用download Manager实现应用下载安装的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/1031194

相关文章

Java Lambda表达式的使用详解

《JavaLambda表达式的使用详解》:本文主要介绍JavaLambda表达式的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、前言二、Lambda表达式概述1. 什么是Lambda表达式?三、Lambda表达式的语法规则1. 无参数的Lambda表

Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析

《Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析》InstantiationAwareBeanPostProcessor是Spring... 目录一、什么是InstantiationAwareBeanPostProcessor?二、核心方法解

IDEA如何实现远程断点调试jar包

《IDEA如何实现远程断点调试jar包》:本文主要介绍IDEA如何实现远程断点调试jar包的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录问题步骤总结问题以jar包的形式运行Spring Boot项目时报错,但是在IDEA开发环境javascript下编译

详解如何使用Python构建从数据到文档的自动化工作流

《详解如何使用Python构建从数据到文档的自动化工作流》这篇文章将通过真实工作场景拆解,为大家展示如何用Python构建自动化工作流,让工具代替人力完成这些数字苦力活,感兴趣的小伙伴可以跟随小编一起... 目录一、Excel处理:从数据搬运工到智能分析师二、PDF处理:文档工厂的智能生产线三、邮件自动化:

Spring @RequestMapping 注解及使用技巧详解

《Spring@RequestMapping注解及使用技巧详解》@RequestMapping是SpringMVC中定义请求映射规则的核心注解,用于将HTTP请求映射到Controller处理方法... 目录一、核心作用二、关键参数说明三、快捷组合注解四、动态路径参数(@PathVariable)五、匹配请

Python实现自动化Word文档样式复制与内容生成

《Python实现自动化Word文档样式复制与内容生成》在办公自动化领域,高效处理Word文档的样式和内容复制是一个常见需求,本文将展示如何利用Python的python-docx库实现... 目录一、为什么需要自动化 Word 文档处理二、核心功能实现:样式与表格的深度复制1. 表格复制(含样式与内容)2

Java 枚举的基本使用方法及实际使用场景

《Java枚举的基本使用方法及实际使用场景》枚举是Java中一种特殊的类,用于定义一组固定的常量,枚举类型提供了更好的类型安全性和可读性,适用于需要定义一组有限且固定的值的场景,本文给大家介绍Jav... 目录一、什么是枚举?二、枚举的基本使用方法定义枚举三、实际使用场景代替常量状态机四、更多用法1.实现接

python获取cmd环境变量值的实现代码

《python获取cmd环境变量值的实现代码》:本文主要介绍在Python中获取命令行(cmd)环境变量的值,可以使用标准库中的os模块,需要的朋友可以参考下... 前言全局说明在执行py过程中,总要使用到系统环境变量一、说明1.1 环境:Windows 11 家庭版 24H2 26100.4061

springboot项目中使用JOSN解析库的方法

《springboot项目中使用JOSN解析库的方法》JSON,全程是JavaScriptObjectNotation,是一种轻量级的数据交换格式,本文给大家介绍springboot项目中使用JOSN... 目录一、jsON解析简介二、Spring Boot项目中使用JSON解析1、pom.XML文件引入依

Java中的record使用详解

《Java中的record使用详解》record是Java14引入的一种新语法(在Java16中成为正式功能),用于定义不可变的数据类,这篇文章给大家介绍Java中的record相关知识,感兴趣的朋友... 目录1. 什么是 record?2. 基本语法3. record 的核心特性4. 使用场景5. 自定