如何在android N上以编程方式安装Application

问题描述 投票:4回答:1

我遵循这些步骤,但对于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示例中所示的pathName,pathValue是系统上的实际路径。放一个“。”是个好主意。对于上面的pathValue,如果你不想添加任何额外的子目录。

3 - 将以下代码写入Run Your 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);
}
android apk android-install-apk
1个回答
0
投票

首先,将目标SDK版本设置为26(Android Oreo)以使一切正常。

然后按照以下步骤操作:

  1. 如何检查是否允许安装?

您可以在活动中使用getPackageManager().canRequestPackageInstalls()查看所有地方。请注意,如果您未声明该权限或选择了错误的SDK版本,则此布尔值始终会重新生成false

  1. 我需要什么许可?

你需要将Mainfest.permission.REQUEST_PACKAGE_INSTALLS声明到你的app清单中,所以这就是:

<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);

© www.soinside.com 2019 - 2024. All rights reserved.