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

相关文章

Conda与Python venv虚拟环境的区别与使用方法详解

《Conda与Pythonvenv虚拟环境的区别与使用方法详解》随着Python社区的成长,虚拟环境的概念和技术也在不断发展,:本文主要介绍Conda与Pythonvenv虚拟环境的区别与使用... 目录前言一、Conda 与 python venv 的核心区别1. Conda 的特点2. Python v

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

C#中Guid类使用小结

《C#中Guid类使用小结》本文主要介绍了C#中Guid类用于生成和操作128位的唯一标识符,用于数据库主键及分布式系统,支持通过NewGuid、Parse等方法生成,感兴趣的可以了解一下... 目录前言一、什么是 Guid二、生成 Guid1. 使用 Guid.NewGuid() 方法2. 从字符串创建

Python使用python-can实现合并BLF文件

《Python使用python-can实现合并BLF文件》python-can库是Python生态中专注于CAN总线通信与数据处理的强大工具,本文将使用python-can为BLF文件合并提供高效灵活... 目录一、python-can 库:CAN 数据处理的利器二、BLF 文件合并核心代码解析1. 基础合

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

golang版本升级如何实现

《golang版本升级如何实现》:本文主要介绍golang版本升级如何实现问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录golanwww.chinasem.cng版本升级linux上golang版本升级删除golang旧版本安装golang最新版本总结gola

PostgreSQL的扩展dict_int应用案例解析

《PostgreSQL的扩展dict_int应用案例解析》dict_int扩展为PostgreSQL提供了专业的整数文本处理能力,特别适合需要精确处理数字内容的搜索场景,本文给大家介绍PostgreS... 目录PostgreSQL的扩展dict_int一、扩展概述二、核心功能三、安装与启用四、字典配置方法

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Mysql实现范围分区表(新增、删除、重组、查看)

《Mysql实现范围分区表(新增、删除、重组、查看)》MySQL分区表的四种类型(范围、哈希、列表、键值),主要介绍了范围分区的创建、查询、添加、删除及重组织操作,具有一定的参考价值,感兴趣的可以了解... 目录一、mysql分区表分类二、范围分区(Range Partitioning1、新建分区表:2、分

MySQL 定时新增分区的实现示例

《MySQL定时新增分区的实现示例》本文主要介绍了通过存储过程和定时任务实现MySQL分区的自动创建,解决大数据量下手动维护的繁琐问题,具有一定的参考价值,感兴趣的可以了解一下... mysql创建好分区之后,有时候会需要自动创建分区。比如,一些表数据量非常大,有些数据是热点数据,按照日期分区MululbU