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

相关文章

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

MySQL中EXISTS与IN用法使用与对比分析

《MySQL中EXISTS与IN用法使用与对比分析》在MySQL中,EXISTS和IN都用于子查询中根据另一个查询的结果来过滤主查询的记录,本文将基于工作原理、效率和应用场景进行全面对比... 目录一、基本用法详解1. IN 运算符2. EXISTS 运算符二、EXISTS 与 IN 的选择策略三、性能对比

Redis客户端连接机制的实现方案

《Redis客户端连接机制的实现方案》本文主要介绍了Redis客户端连接机制的实现方案,包括事件驱动模型、非阻塞I/O处理、连接池应用及配置优化,具有一定的参考价值,感兴趣的可以了解一下... 目录1. Redis连接模型概述2. 连接建立过程详解2.1 连php接初始化流程2.2 关键配置参数3. 最大连

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买

Python标准库之数据压缩和存档的应用详解

《Python标准库之数据压缩和存档的应用详解》在数据处理与存储领域,压缩和存档是提升效率的关键技术,Python标准库提供了一套完整的工具链,下面小编就来和大家简单介绍一下吧... 目录一、核心模块架构与设计哲学二、关键模块深度解析1.tarfile:专业级归档工具2.zipfile:跨平台归档首选3.

使用Python构建智能BAT文件生成器的完美解决方案

《使用Python构建智能BAT文件生成器的完美解决方案》这篇文章主要为大家详细介绍了如何使用wxPython构建一个智能的BAT文件生成器,它不仅能够为Python脚本生成启动脚本,还提供了完整的文... 目录引言运行效果图项目背景与需求分析核心需求技术选型核心功能实现1. 数据库设计2. 界面布局设计3

使用IDEA部署Docker应用指南分享

《使用IDEA部署Docker应用指南分享》本文介绍了使用IDEA部署Docker应用的四步流程:创建Dockerfile、配置IDEADocker连接、设置运行调试环境、构建运行镜像,并强调需准备本... 目录一、创建 dockerfile 配置文件二、配置 IDEA 的 Docker 连接三、配置 Do

Android Paging 分页加载库使用实践

《AndroidPaging分页加载库使用实践》AndroidPaging库是Jetpack组件的一部分,它提供了一套完整的解决方案来处理大型数据集的分页加载,本文将深入探讨Paging库... 目录前言一、Paging 库概述二、Paging 3 核心组件1. PagingSource2. Pager3.

深入浅出SpringBoot WebSocket构建实时应用全面指南

《深入浅出SpringBootWebSocket构建实时应用全面指南》WebSocket是一种在单个TCP连接上进行全双工通信的协议,这篇文章主要为大家详细介绍了SpringBoot如何集成WebS... 目录前言为什么需要 WebSocketWebSocket 是什么Spring Boot 如何简化 We

Java Stream流之GroupBy的用法及应用场景

《JavaStream流之GroupBy的用法及应用场景》本教程将详细介绍如何在Java中使用Stream流的groupby方法,包括基本用法和一些常见的实际应用场景,感兴趣的朋友一起看看吧... 目录Java Stream流之GroupBy的用法1. 前言2. 基础概念什么是 GroupBy?Stream