安装下载的 apk 文件时通过 Intent.getData() 错误暴露在应用程序之外

Pra*_*eep 5 android

我已经从服务器下载了 apk 文件,现在正在安装它,但它给了我一个错误:通过 Intent.getData() 在应用程序之外暴露

我的代码是

Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);


        intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() +
                "/download/" + "in.sample.myapp.apk")), "application/vnd.android.package-archive");
Run Code Online (Sandbox Code Playgroud)

我已经搜索了错误并找到了一些但无法解决问题。建议使用 FileProvider。我这样做只是为了检查日志

Log.d("NewPath", "NewPathName is: " +(FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider",outputFile)));
Run Code Online (Sandbox Code Playgroud)

可以帮助解决这个问题。

请帮忙和建议。

Mey*_*ari 7

你的代码

Intent intent = new Intent(Intent.ACTION_VIEW);
File file = new File(Environment.getExternalStorageDirectory() + "/FolderName/" + "yourFile.apk");
Uri data = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID +".provider",file);
intent.setDataAndType(data,"application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.startActivity(intent);
Run Code Online (Sandbox Code Playgroud)

文件路径.xml

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>
Run Code Online (Sandbox Code Playgroud)

显现

<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/filepaths"/>
    </provider>
</application>
Run Code Online (Sandbox Code Playgroud)


Shi*_*yal 2

使用FileProvider,示例代码如下:

    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri data = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider" ,file);
    intent.setDataAndType(data, "/*");
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    context.startActivity(intent);
Run Code Online (Sandbox Code Playgroud)

此外,您还需要在清单文件中包含 FileProvider 在应用程序标记内,只需执行以下操作:

    <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>
Run Code Online (Sandbox Code Playgroud)

同样在资源目录下创建xml文件夹,并创建文件provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">

    <external-path name="PATH here" path=""/>
</paths>
Run Code Online (Sandbox Code Playgroud)