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中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

C++中unordered_set哈希集合的实现

《C++中unordered_set哈希集合的实现》std::unordered_set是C++标准库中的无序关联容器,基于哈希表实现,具有元素唯一性和无序性特点,本文就来详细的介绍一下unorder... 目录一、概述二、头文件与命名空间三、常用方法与示例1. 构造与析构2. 迭代器与遍历3. 容量相关4

Linux join命令的使用及说明

《Linuxjoin命令的使用及说明》`join`命令用于在Linux中按字段将两个文件进行连接,类似于SQL的JOIN,它需要两个文件按用于匹配的字段排序,并且第一个文件的换行符必须是LF,`jo... 目录一. 基本语法二. 数据准备三. 指定文件的连接key四.-a输出指定文件的所有行五.-o指定输出

Linux jq命令的使用解读

《Linuxjq命令的使用解读》jq是一个强大的命令行工具,用于处理JSON数据,它可以用来查看、过滤、修改、格式化JSON数据,通过使用各种选项和过滤器,可以实现复杂的JSON处理任务... 目录一. 简介二. 选项2.1.2.2-c2.3-r2.4-R三. 字段提取3.1 普通字段3.2 数组字段四.

C++中悬垂引用(Dangling Reference) 的实现

《C++中悬垂引用(DanglingReference)的实现》C++中的悬垂引用指引用绑定的对象被销毁后引用仍存在的情况,会导致访问无效内存,下面就来详细的介绍一下产生的原因以及如何避免,感兴趣... 目录悬垂引用的产生原因1. 引用绑定到局部变量,变量超出作用域后销毁2. 引用绑定到动态分配的对象,对象

Linux kill正在执行的后台任务 kill进程组使用详解

《Linuxkill正在执行的后台任务kill进程组使用详解》文章介绍了两个脚本的功能和区别,以及执行这些脚本时遇到的进程管理问题,通过查看进程树、使用`kill`命令和`lsof`命令,分析了子... 目录零. 用到的命令一. 待执行的脚本二. 执行含子进程的脚本,并kill2.1 进程查看2.2 遇到的

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置