以编程方式在 Android 7 / api24 中安装 apk

Programmatically install an apk in Android 7 / api24

我正在尝试让我的应用程序自动安装 apk。这适用于 api<24。但是对于 24,它是失败的。 Android 已实施额外的安全措施:

For apps targeting Android 7.0, the Android framework enforces the StrictMode API policy that prohibits exposing file:// URIs outside your app. If an intent containing a file URI leaves your app, the app fails with a FileUriExposedException exception.

所以我尝试了这个:

    Uri myuri;
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N){
        myuri = Uri.parse("file://"+outapk);
    } else {
        File o = new File(outapk);
        myuri = FileProvider.getUriForFile(con, con.getApplicationContext().getPackageName() + ".provider", o);
    }
    Intent promptInstall = new Intent(Intent.ACTION_VIEW).setDataAndType(myuri,"application/vnd.android.package-archive");
    con.startActivity(promptInstall);

但出现致命异常:

com.android.packageinstaller "Caused by: java.lang.SecurityException: Permission Denial: opening provider android.support.v4.content.FileProvider from ProcessRecord{b42ee8a 6826:com.android.packageinstaller/u0a15} (pid=6826, uid=10015) that is not exported from uid 10066". 

我的清单中有 export=true。

问题似乎是 packageinstaller 不能使用 content:// uri。

是否有任何方法可以让应用程序以编程方式安装带有 api24 的 apk?

Are there any ways to allow an app to progammatically install an apk with api24?

addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) 添加到您的 promptInstall 设置中,以授予对内容的读取权限。

I have export=true in my manifest.

不在您的 FileProvider 上,因为那样会导致您的应用程序崩溃。

The problem seems to be that packageinstaller cannot use a content:// uri.

不,问题是您没有授予包安装程序读取该 Uri 的权限。如果软件包安装程序无法使用 content 方案,您将获得 ActivityNotFoundException.

不过请注意,只有 Android 7.0 包安装程序才开始支持 content。 Android 的早期版本必须使用 file.

res/xml 添加文件 -> provider_paths.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>

AndroidManifest.xml

中添加此代码
     <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.example.provider" <-- change this with your package name
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>

运行 此代码用于安装您的应用或打开

    public void installApk(String file) {
        Uri uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider",new File(file));
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        context.startActivity(intent);
    }

对于奥利奥, 在 AndroidManifest

中添加权限
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>

对于Oreo,在AndroidManifast中添加权限(否则它只是默默地失败)

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

现在添加到您的清单

  <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/provider_paths"/>
</provider>

在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>

然后在您需要的地方使用这些代码。

File directory = Environment.getExternalStoragePublicDirectory("myapp_folder"); 

 File file = new File(directory, "myapp.apk"); // assume refers to "sdcard/myapp_folder/myapp.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 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_NEW_TASK);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //dont forget add this line
    context.startActivity(intent);
}

只需执行以下步骤:

1- 将以下权限添加到清单中:

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

2- 将提供程序添加到清单(作为子应用程序标记):

 <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="tatcomputer.ir.libraryapp.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/paths"/>
    </provider>

3- 添加 paths.xml 到 xml 目录:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="files" path="." />
<external-files-path name="external_files" path="." />
<external-path name="external_files" path="." />
<cache-path name="cached_files" path="." />
<external-cache-path name="cached_files" path="." />
</paths>

4- 使用以下代码显示安装 apk 页面(请注意,在我的例子中,apk 位于我的 phone 的根目录中,名为 tmp.apk:

       String root = Environment.getExternalStorageDirectory().toString();

        Uri fileUri24 = FileProvider.getUriForFile(App.applicationContext, BuildConfig.APPLICATION_ID + ".provider", new File(root + "/tmp.apk"));
        Uri fileUri = Uri.fromFile(new File(root + "/tmp.apk"));

        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= 24)
            intent.setDataAndType(fileUri24, "application/vnd.android.package-archive");
        else intent.setDataAndType(fileUri, "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        App.applicationContext.startActivity(intent);

这是我找到的解决方案

val newFile = File(dirPath, "$fileNameWithoutExtn.apk")
                        var fileUri = Uri.fromFile(newFile)
                        //use the fileProvider to get the downloaded from sdcard
                        if (Build.VERSION.SDK_INT >= 24) {
                            fileUri = FileProvider.getUriForFile(this@SettingAcitivity, applicationContext.packageName + ".provider", newFile)
                         val intent=Intent(Intent.ACTION_VIEW)
                            intent.setDataAndType(fileUri, "application/vnd.android.package-archive")
                            intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
                            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                            startActivity(intent)
                        }else{
                            newFile.setReadable(true, false)
                            val intent = Intent(Intent.ACTION_VIEW)
                            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
                            intent.setDataAndType(fileUri, "application/vnd.android.package-archive")
                            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                            startActivity(intent)
                        }

并写入清单

<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"/>

并设置权限

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

在 xml 中,文件夹路径将为

<paths>
    <external-path
        name="external_files"
        path="." />
</paths>

自动安装 Apk

Intent intent1 = new Intent(Intent.ACTION_INSTALL_PACKAGE);
            intent1.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent1.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" +filename)), "application/vnd.android.package-archive");
            intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

就我而言 android 8.0 问题出在

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

更详细的如何获得这个权限Exception 'open failed: EACCES (Permission denied)' on Android