通过FileProvider跨Android用户共享文件
我希望与运行有通过FileProvider跨Android用户共享文件,android,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 我启动服务以共享此文件,如
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);
但是,当我在我的FileShareService中收到除UserHandle.user\u所有者以外的任何用户发送的意图时,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中的文件提供程序和服务:
<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>
我最终使用了一个带有
android:singleUser=“true”
和android:exported=“true”
的文档提供者,而不是文件提供者
设置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();