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

相关文章

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

Python使用国内镜像加速pip安装的方法讲解

《Python使用国内镜像加速pip安装的方法讲解》在Python开发中,pip是一个非常重要的工具,用于安装和管理Python的第三方库,然而,在国内使用pip安装依赖时,往往会因为网络问题而导致速... 目录一、pip 工具简介1. 什么是 pip?2. 什么是 -i 参数?二、国内镜像源的选择三、如何

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

Linux使用nload监控网络流量的方法

《Linux使用nload监控网络流量的方法》Linux中的nload命令是一个用于实时监控网络流量的工具,它提供了传入和传出流量的可视化表示,帮助用户一目了然地了解网络活动,本文给大家介绍了Linu... 目录简介安装示例用法基础用法指定网络接口限制显示特定流量类型指定刷新率设置流量速率的显示单位监控多个

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本