使用FileProvider在Android用户之间共享文件

时间:2015-03-09 23:13:58

标签: android

我希望与运行android:singleUser属性的服务共享文件。该文件将保存到Android用户的本地数据目录中。所以这可能是以下之一:

  • /data/user/0/com.example.fileshare/files/myfile.txt
  • /data/user/10/com.example.fileshare/files/myfile.txt
  • /data/user/11/com.example.fileshare/files/myfile.txt

我启动服务以共享此文件,如:

Uri fileUri = FileProvider.getUriForFile(getApplicationContext(), "com.example.fileshare.fileprovider", file);

Log.d(TAG, "Share File URI: " + fileUri.toString());

Intent shareFileIntent = new Intent(getApplicationContext(), FileSharingService.class);
shareFileIntent.setAction(Intent.ACTION_SEND);
shareFileIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
String mimeType = getContentResolver().getType(fileUri);
Log.d(TAG, "Share File MIME Type: " + mimeType);
shareFileIntent.setDataAndType(
     fileUri,
     mimeType);

startService(shareFileIntent);

但是当我收到FileSharingService中UserHandle.USER_OWNER之外的任何用户发送的意图时,ContentResolver无法找到该文件,因为该文件不存在于运行该服务的同一用户数据目录中android:singleUser属性。

@Override
protected void onHandleIntent(Intent intent) {
    Log.d(TAG, "onHandleIntent - " + intent.getAction());

    if (Intent.ACTION_SEND.equals(intent.getAction())) {
        Uri fileUri = intent.getData();

        // When I try and read the file it says that the file does not exist. 
        FileInputStream in = getContentResolver().openInputStream(fileUri);
    }
}

以下是AndroidManifest.xml中的FileProvider和Service:

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.example.fileshare.fileprovider"
    android:grantUriPermissions="true" >
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

<service
    android:name="com.example.fileshare.FileSharingService"
    android:exported="true"
    android:singleUser="true" >
    <intent-filter>
        <action android:name="android.intent.action.SEND" />

        <category android:name="android.intent.category.DEFAULT" />

        <data android:mimeType="*/*" />
    </intent-filter>
</service>

1 个答案:

答案 0 :(得分:1)

我最终使用了一个带有android:singleUser="true"android:exported="true"而不是FileProvider的DocumentsProvider。

在设置了DocumentsProvider的子类之后,我可以使用这段代码创建一个新文档,并将文件的内容从一个用户写入已解析的Uri返回。

final ContentResolver resolver = getContentResolver();
Uri derivedUri = DocumentsContract.buildDocumentUri(
                        "com.example.documentsprovider.authority", "root");
client = acquireUnstableProviderOrThrow(
                        resolver, "com.example.documentsprovider.authority");
childUri = DocumentsContract.createDocument(
                        client, derivedUri, mimeType, displayName);


InputStream in = mContext.getContentResolver().openInputStream(myFileUri);
OutputStream os = mContext.getContentResolver().openOutputStream(childUri);

byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
    os.write(buf, 0, len);
}

in.close();
os.close();
相关问题