具体代码

    /*** 下载目录*/private String filepath = "/.***/";/*** apk名称*/private String filepaths = "***.apk";private String flil = "";/*** 下载链接*/private String mUrl = "http://www.***.com/***.apk";
    if (ToolUtil.isAvilible(getApplicationContext(),"需检测的apk包名")){ComponentName componentName = new ComponentName("跳转的目标apk包名","跳转的目标apk的activity(全路径)");Intent intent = new Intent();intent.setComponent(componentName);startActivityForResult(intent, REQUEST_CODE);}else if (ToolUtil.fileIsExists(flil)){ToolUtil.installApk(getApplicationContext(),new File(flil));}else {//跳转浏览器下载//ToolUtil.openBrowser(getApplicationContext(),mUrl);//Android自带的下载管理器DownloadUtils.builder().setContext(getApplicationContext()).setFileName(filepaths).setUrl(mUrl).setFILE_URI(filepath).setLister(new DownloadUtils.IDownloadlister() {@Overridepublic void success(Uri uri) {Intent install = new Intent(Intent.ACTION_VIEW);install.setDataAndType(uri, "application/vnd.android.package-archive");install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);startActivity(install);}}).download();}

文件下载工具类DownloadUtils

public class DownloadUtils {//定义一个成功接口public interface IDownloadlister {void success(Uri uri);}private DownloadManager downloadManager;//下载链接private String url = "";//对于/.followUpBox/来说加.好处是默认隐藏路径private String FILE_URI = "";private IDownloadlister lister = null;//文件名private String fileName = "";//上下文private Context context;//下载完成后跳转安装private BroadcastReceiver mBroadcastReceiver=new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {checkStatus(context,intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1));}};public static DownloadUtils builder() {return new DownloadUtils();}public DownloadUtils setUrl(String url) {this.url = url;return this;}public DownloadUtils setLister(IDownloadlister lister) {this.lister = lister;return this;}public DownloadUtils setFileName(String fileName) {this.fileName = fileName;return this;}public DownloadUtils setFILE_URI(String FILE_URI) {this.FILE_URI = FILE_URI;return this;}public DownloadUtils setContext(Context context) {this.context = context;return this;}public void download() {IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);//创建下载任务,url即任务链接DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));//指定下载路径及文件名request.setDestinationInExternalPublicDir(FILE_URI, fileName);//获取下载管理器downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);//一些配置//允许移动网络与WIFI下载request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);//是否在通知栏显示下载进度request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);//设置可见及可管理/*注意,Android Q之后不推荐使用*/request.setVisibleInDownloadsUi(true);//将任务加入下载队列assert downloadManager != null;final long id = downloadManager.enqueue(request);//下载完成后跳转安装context.registerReceiver(mBroadcastReceiver,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));BroadcastReceiver receiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {//获取下载idlong myDwonloadID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);if (myDwonloadID == id) {//获取下载uriUri uri = downloadManager.getUriForDownloadedFile(myDwonloadID);lister.success(uri);}}};if (context instanceof Activity) {Activity activity = (Activity) context;activity.registerReceiver(receiver, filter);}}/*** 检查下载状态*/private void checkStatus(Context context,long Id) {DownloadManager.Query query = new DownloadManager.Query();query.setFilterById(Id);Cursor cursor = downloadManager.query(query);if (cursor.moveToFirst()) {int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));switch (status) {//下载暂停case DownloadManager.STATUS_PAUSED:break;//下载延迟case DownloadManager.STATUS_PENDING:break;//正在下载case DownloadManager.STATUS_RUNNING:break;//下载完成case DownloadManager.STATUS_SUCCESSFUL:ToolUtil.installApk(context,new File(String.valueOf(Environment.getExternalStoragePublicDirectory(FILE_URI+fileName))));break;//下载失败case DownloadManager.STATUS_FAILED:Toast.makeText(context.getApplicationContext(), "下载失败", Toast.LENGTH_SHORT).show();break;}}cursor.close();}
}

杂项工具类ToolUtil

public class ToolUtil {/*** 调用第三方浏览器打开* @param context 上下文* @param url 要浏览的资源地址*/public static void openBrowser(Context context, String url){final Intent intent = new Intent();intent.setAction(Intent.ACTION_VIEW);intent.setData(Uri.parse(url));PackageManager b = context.getPackageManager();ComponentName a = intent.resolveActivity(b);// 注意此处的判断intent.resolveActivity()可以返回显示该Intent的Activity对应的组件名// 官方解释 : Name of the component implementing an activity that can display the intentif (intent.resolveActivity(context.getPackageManager()) != null) {final ComponentName componentName = intent.resolveActivity(context.getPackageManager());// 打印Log   ComponentName到底是什么L.d("componentName = " + componentName.getClassName());context.startActivity(Intent.createChooser(intent, "请选择浏览器"));} else {Toast.makeText(context.getApplicationContext(), "链接错误或无浏览器", Toast.LENGTH_SHORT).show();}}/*** 检测Android是否安装了某个程序* @param context 上下文* @param packageName 程序包名* @return*/public static boolean isAvilible(Context context, String packageName) {final PackageManager packageManager = context.getPackageManager();// 获取所有已安装程序的包信息List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);for ( int i = 0; i < pinfo.size(); i++ ) {if(pinfo.get(i).packageName.equalsIgnoreCase(packageName))return true;}return false;}/*** 判断文件是否存在* @param filePath 文件路径* @return*/public static boolean fileIsExists(String filePath) {try {File f = new File(filePath);if(!f.exists()) {return false;}} catch (Exception e) {return false;}return true;}/*** 安装apk* @param context* @param apkFile*/public static void installApk(Context context, File apkFile){Intent intent = new Intent(Intent.ACTION_VIEW);//由于没有在Activity环境下启动Activity,所以设置下面的标签intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);Uri apkUri = null;//判断版本是否是 7.0 及 7.0 以上if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {apkUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", apkFile);//添加这一句表示对目标应用临时授权该Uri所代表的文件intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);} else {apkUri = Uri.fromFile(apkFile);}intent.setDataAndType(apkUri, "application/vnd.android.package-archive");context.startActivity(intent);}}

配置文件里添加

广播权限

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

文件读取

<providerandroid:name="android.support.v4.content.FileProvider"android:authorities="APP包名.fileprovider"android:exported="false"android:grantUriPermissions="true"><meta-dataandroid:name="android.support.FILE_PROVIDER_PATHS"android:resource="@xml/file_paths" />
</provider>

file_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<resources><paths><external-path path ="" name = "download"/></paths>
</resources>

下载安装包到本地,安装等相关推荐

  1. Python在cmd下pip快速下载安装包的国内安装镜像

    cmd下安装报pip版本太老的错 python -m pip install --upgrade pip 下载安装包临时使用镜像可以加快下载速度 pip install numpy -i https: ...

  2. python官网下载安装包滴滴专车-安装python2.7

    1.安装Development Tools yum groupinstall -y "development tools" 2安装SSL.bz2.zlib来为Python的安装做好 ...

  3. 从阿里云下载kubeadm rpm格式安装包到本地离线安装

    从阿里云下载kubeadm rpm格式安装包到本地 ①.配置yum源 # cat <<EOF > /etc/yum.repos.d/kubernetes.repo [kubernet ...

  4. r语言从网页下载东西内容 r安装特定版本的r包 r从网页下载 安装包

    加载 library(RCurl) getBinaryURL(url, -, .opts = list(), curl = getCurlHandle(), .buf = binaryBuffer(. ...

  5. 记录一次成功安装PyTorch(Win版)(直接下载安装包式的pip安装)

    1.由于网上教程很多,本人顺利的部分(1.更新nvidia驱动;2.CUDA10安装;3.cuDNN 7 安装)不赘述,建议参考该链接: windows10下安装GPU版pytorch简明教程 - 知 ...

  6. npm 包与模块关系 下载使用包 init命令 package.json文件 node_modules文件夹 全局安装包和本地安装包 开发依赖和生产依赖

    npm 了解npm npm 全称Node Package Manager(node 包管理器),它的诞生是为了解决 Node 中第三方包共享的问题. npm 不需要单独安装.在安装Node的时候,会连 ...

  7. MAC下安装ElasticSearch(官网下载安装包)

    1.基础环境准备 Elasticsearch 依赖于JDK, 并且JDK 版本1.8+ 检验jdk  命令 : java -version 2.下载安装包 去官网下载https://www.elast ...

  8. CentOS yum安装软件时保留安装包及依赖包或者自动下载安装包及相关依赖包

    方式一 使用yum安装软件 yum -y install openssh 升级结束后去cachedir下将所有目录下的rpm文件取出组合在一起即为当前安装软件所需的所有文件 使用yum downloa ...

  9. android_ android apk analyzer(libchecker apk分析器):分析Android手机上已安装的app(库/基础组件分析/开发技术)/从酷安市场下载安装包

    android apk analyzer(libchecker apk分析器):分析Android手机上已安装的app(库/基础组件分析/开发技术-) download app(apk) Releas ...

最新文章

  1. win10 看不到其它计算机,w10网上邻居搜索不到其它电脑怎么办
  2. Laravel——消息通知
  3. win2003系统+IIS6下,经常出现w3wp.exe和sqlserver.exe的内存占用居高不下
  4. Python中多个数组行合并及列合并的方法总结
  5. lower_bound upper_bound
  6. vim 编译 Python 代码提示配置
  7. [CQOI2012] 局部极小值(状压DP + 容斥 + 搜索)
  8. CentOS6 下Samba服务器的安装与配置
  9. 音乐播放器 audio
  10. flutter DateTime 日期时间详细解析 Dart语言基础
  11. final/finalize/finally的区别
  12. 分类二级联动 php,学习猿地-php实现二级联动菜单
  13. Flutter打包apk中的一些巨坑
  14. 服务器入站规则 共享文件,How to :发布内部网络中的文件共享服务
  15. Vbs判断两个Excel文件的内容--将两个Excel文件相同内容写入新建的Excel文件内
  16. 黑马python5_黑马Python5.0+人工智能课程升级5.0版本!【完整无秘】
  17. 伺服电机功率计算选型与伺服电机惯量匹配
  18. 销售宝:购买财务软件需要注意的5个方面
  19. Python编写时钟表turtle
  20. Java基础:常用类(String类)

热门文章

  1. html地图交互式显示信息,HTML5 交互式SVG六边形蜂巢状地图 悬停放大并显示提示文本...
  2. 线程锁及线程锁的作用
  3. 2022年终总结:不一样的形式,不一样的展现
  4. 领导要懂敏捷吗?看丰田黄金搭档三人组
  5. 实战干货:Python3小说站点爬虫|附下载
  6. Unity中父子物体的坑
  7. 小米10s真的划算吗?
  8. An HTTP error occurred when trying to retrieve this URL.(解决方案)
  9. ASO信息流投放优势及技巧分享会
  10. 多线程爬虫获取平板电脑信息