我正在为自己的Android应用构建自己的更新机制(我没有使用Play商店)。我可以使用DownloadManager
成功下载新的APK。下载完成后,我想提示用户安装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存储中(取决于可用空间的多少)。
我该如何解决问题?
答案 0 :(得分:1)
可能的Install Application programmatically on Android副本
我认为该线程的答案应该有效:
https://stackoverflow.com/a/54424223/9490453
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>