如何在Android N上通过编程方式安装应用程序

5
我正在按照以下步骤进行操作,但是在SDK版本N上,在安装应用程序时,Android系统会显示一个警告对话框“包安装器已停止”。
1 - 将以下内容添加到AndroidManifest.xml中:
<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="${applicationId}.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/paths"/>
</provider>

2- 将以下paths.xml文件添加到src/main/res/xml文件夹中(如果不存在,请创建它)。
 <?xml version="1.0" encoding="utf-8"?>
 <paths xmlns:android="http://schemas.android.com/apk/res/android">
 <external-path
 name="external_file"
 path="."/>
</paths>
pathName是上面示例内容URI中显示的路径名称,pathValue是系统上实际的路径。如果您不想添加任何额外的子目录,建议在上面的pathValue中放置一个“.”。
3-编写以下代码以运行您的APK文件:
File file = "path of yor apk file";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 Uri fileUri = FileProvider.getUriForFile(getBaseContext(), 
 getApplicationContext().getPackageName() + ".provider", file);
 Intent intent = new Intent(Intent.ACTION_VIEW, fileUri);
 intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true) ;
 intent.setDataAndType(fileUri, "application/vnd.android" + ".package-
 archive");
 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | 
 Intent.FLAG_ACTIVITY_NEW_TASK);
 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
 startActivity(intent);

} else {
   Intent intent = new Intent(Intent.ACTION_VIEW);

  intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-
  archive");
  intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  startActivity(intent);
}

据我所知,您无法通过另一个应用程序以编程方式安装应用程序。最多只能下载文件,我之前也尝试过同样的事情,它需要用户授权才能安装该应用程序。 - sunilkarkala
1
它在除了 Android N 版本之外的所有版本上都能完美地工作。 - raman
1个回答

1
首先,将目标SDK版本设置为26(Android Oreo),以使一切正常运行。
然后按照以下步骤操作:
  1. 如何检查是否允许安装?

您可以在活动中使用getPackageManager().canRequestPackageInstalls()检查任何地方。请注意,如果您未声明该权限或选择错误的SDK版本,则此布尔值始终返回false

  1. 我需要请求哪些权限?

您需要在应用程序清单中声明Mainfest.permission.REQUEST_PACKAGE_INSTALLS,因此在此处:

<uses-permission android:name="android.permission.REQUEST_PACKAGE_INSTALLS" />
  1. 如何提示用户授予权限?

您可以像这样做:

startActivity(new Intent(android.provider.Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:".concat("your.package.name"))));

一旦您完成了所有其他步骤,您可以使用以下代码提示用户安装包:
  1. 如何提示用户安装apk?

完成所有其他步骤后,您可以使用此代码提示用户安装软件包:

Intent installIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
installIntent.putExtra(Intent.EXTRA_RETURN_RESULT, true); //this is necessary if you want to know if the installation was success, failed or cancelled.
installIntent.setData(Uri.fromFile(new File("/sdcard/yourapk.apk"))); //replace yourapk to your apk name
startActivityForResult(installIntent, 1);

如果您想知道安装是否成功、失败或取消,您可能还需要添加installIntent.putExtra(Intent.EXTRA_RETURN_RESULT, true);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接