美文网首页Android
安卓FileProvider

安卓FileProvider

作者: 蓝不蓝编程 | 来源:发表于2023-02-12 21:47 被阅读0次

1. 修改AndroidManifest.xml

添加:

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.FileProvider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

2. res目录下增加xml目录,xml目录下增加file_paths.xml

内容:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="external_files" path="." />
    <files-path name="files-path" path="." />
    <cache-path name="cache-path" path="." />
    <external-files-path name="external_file_path" path="." />
    <external-cache-path name="external_cache_path" path="." />
    <root-path name="root-path" path="" />
</paths>

3. 使用代码

void test(Activity activity) {
    String filePath = Environment.getExternalStorageDirectory().getPath() + "/Download/test.apk";
    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri uri;

    File file = new File(filePath);
    if (Build.VERSION.SDK_INT >= 24) {//android 7.0以上
        //第二个参数:"app的包名.fileProvider"
        uri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID.concat(".FileProvider"), file);
    } else {
        uri = Uri.fromFile(file);
    }
    String type = "application/vnd.android.package-archive";
    intent.setDataAndType(uri, type);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    if (Build.VERSION.SDK_INT >= 24) {
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        int flag = Intent.FLAG_GRANT_READ_URI_PERMISSION;
        activity.grantUriPermission("com.android.packageinstaller", uri, flag);
    }
    activity.startActivity(intent);
}

相关文章

网友评论

    本文标题:安卓FileProvider

    本文链接:https://www.haomeiwen.com/subject/ffddkdtx.html