使用FileProvider共享文件


使用第三方应用打开本应用的文件,主要是要处理在Android 7.0及以上的权限问题。为了提高私有文件的安全性,面向 Android 7.0 或更高版本的应用私有目录被限制访问 (0700)。此设置可防止私有文件的元数据泄漏。所以,如果一个应用想让外部应用打开自己应用内文件,需要在配置上:

添加FileProvider,如下所示:

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

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

    <application
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name="..."></activity>

        <!-- 这里是重点 -->
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.tuboshu.scan.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">

            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>
        <!-- 重点结束 -->

    </application>

</manifest>

同时提供上面AndroidManefist.xml中指定的xml文件,即@xml/file_paths,如下所述:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <files-path name="files-path" path="."/>
    <external-path name="external-path" path="."/>
    <external-path name="download" path="download/"/>
</paths>

基于以上配置,我们就可以快乐的写代码了:

public static void openFileByThirdParty(Context context, String mimeType,String filePath) {
    Intent intent = new Intent();

    intent.setAction(Intent.ACTION_VIEW);
    intent.addCategory(Intent.CATEGORY_DEFAULT);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    Uri uri = null;
    File fileObj = new File(filePath);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", fileObj);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    } else {
        uri = Uri.fromFile( fileObj );
    }

    intent.setDataAndType(uri, mimeType);

    context.startActivity(context,intent);
}

以上代码做了自适应,对于低于7.0的版本也适用。

相关标签

扫一扫

在手机上阅读