使用FileProvider共享内部存储

时间:2017-11-19 17:49:12

标签: android sharing android-fileprovider

我想要的是在我的应用程序之间共享文件。我尝试使用文件提供程序,但它没有用。

首先在我的插件应用程序中,我已经设置了一个文件提供程序:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mdl.test.plug">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".ModuleActivity"
        android:label="@string/title_activity_module"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

    </activity>

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.mdl.test.plug.fileprovider"
        android:grantUriPermissions="true"
        android:exported="false">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/filepaths" />
    </provider>

</application>

我的filepaths.xml:

 <paths>
    <files-path path="/" name="allfiles" />
</paths

在Core应用程序中,我尝试阅读test.txt:

Uri uri = Uri.parse("content://com.mdl.test.plug.fileprovider/allfiles/test.txt");
    InputStream is = null;
    StringBuilder result = new StringBuilder();
    try {
        is = getApplicationContext().getContentResolver().openInputStream(uri);
        BufferedReader r = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = r.readLine()) != null) {
            result.append(line);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try { if (is != null) is.close(); } catch (IOException e) { }
    }

但它返回一个权限错误:

Permission Denial: opening provider android.support.v4.content.FileProvider from ProcessRecord

我想要的是Core可以从Plug而不是Plug发送文件到Core读取文件。任何解决方案?

由于

1 个答案:

答案 0 :(得分:1)

  

但是它返回了一个权限错误

这是因为核心应用程序没有Uri的权限。您必须通过插件应用程序授予权限,方法是让插件应用程序使用一些基于Intent的IPC(startActivity()startService()sendBroadcast()等),在{&#34;数据&#34;中包含Uri的位置Intent的方面并使用FLAG_GRANT_READ_URI_PERMISSION

  

我想要的是Core可以从Plug而不是Plug发送文件到Core

读取文件

如果不允许任何其他应用从插件应用中读取文件,这很难做到。

如果您的minSdkVersion为21或更高,则可以创建自己的ContentProvider导出并使用自定义权限进行自我保护。核心应用程序将拥有该权限的<uses-permission>元素,然后它可以随时发出ContentProvider的请求。如果您将自定义权限授予android:protectionLevel signature,那么您的通信应该是安全的,但这需要核心应用和插件应用使用相同的签名密钥进行签名。但是,如果您的minSdkVersion低于21,则自定义权限会出现一些安全问题。

相关问题