android - 提示用户安装 APK
问题描述
我正在为我的 Android 应用程序构建自己的更新机制(我没有使用 Play 商店)。我可以使用DownloadManager
. 下载完成后,我想提示用户安装 apk。我尝试了以下方法:
File file = context.getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS + "/app-debug.apk");
String test = file.getAbsolutePath();
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
.setDataAndType(Uri.parse("content://" + file.getAbsolutePath()),
"application/vnd.android.package-archive");
context.startActivity(promptInstall);
不幸的是,这根本不起作用。该文件在那里,但没有安装提示。出了什么问题?我是否还必须使第二个参数适应setDataAndType
?它应该适用于 SDK 23 到 29。
编辑:
我现在尝试了以下方法:
File file = context.getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS + "/app-debug.apk");
Uri fileUri = Uri.fromFile(file); //for Build.VERSION.SDK_INT <= 24
if (Build.VERSION.SDK_INT >= 24) {
fileUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);
}
Intent promptInstall = new Intent(Intent.ACTION_VIEW, fileUri);
promptInstall.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
promptInstall.setDataAndType(fileUri, "application/vnd.android.package-archive");
promptInstall.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK);
promptInstall.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.startActivity(promptInstall);
在清单中,我现在有以下内容:
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="ir.greencode"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/path" />
</provider>
我已经创建了 path.xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="." /></paths>
但现在我收到错误消息:
java.lang.IllegalArgumentException:找不到具有权限 com.testapp.provider 的提供者的元数据
我下载的 APK 位于/storage/emulated/0/Android/data/com.testapp/files/Download/app-debug.apk
. 这意味着file
指向该目录。最后,我想将 apk 存储在内部存储或 SD 存储中(取决于有更多可用空间)。
我该如何解决这个问题?
解决方案
我认为该线程的这个答案应该有效:
https://stackoverflow.com/a/54424223/9490453
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
推荐阅读
- django - 系统检查无错误后,Django runserver 不执行任何操作
- php - 使用 php 准备的语句将图像(blob)插入 mysql 数据库
- laravel - 一对多关系 Laravel 出现错误
- linkedin - 如何通过 LinkedIn API v2 / UGC Post API 发布(不分享)文章
- javascript - Vue 对象更改,但不会重新渲染
- c - 为什么这个内核映像不能在 QEMU 上启动
- node.js - NodeJS 配置默认环境
- python - 有没有办法在python中洗牌?
- javascript - NodeJS + Mongo - 如何与我的 DOM 从数据库中获取数据进行交互?
- scala - 如何将 S3 存储桶中的 csv 文件转换为 RDD