【发布时间】:2017-04-03 20:36:24
【问题描述】:
我正在将文件保存在内部存储中。它只是一个包含一些对象信息的 .txt 文件:
FileOutputStream outputStream;
String filename = "file.txt";
File cacheDir = context.getCacheDir();
File outFile = new File(cacheDir, filename);
outputStream = new FileOutputStream(outFile.getAbsolutePath());
outputStream.write(myString.getBytes());
outputStream.flush();
outputStream.close();
然后我正在创建一个“shareIntent”来共享这个文件:
Uri notificationUri = Uri.parse("content://com.package.example/file.txt");
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, notificationUri);
shareIntent.setType("text/plain");
context.startActivity(Intent.createChooser(shareIntent, context.getResources().getText(R.string.chooser)));
所选应用现在需要访问私有文件,因此我创建了一个内容提供程序。我只是更改了 openFile 方法:
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
File privateFile = new File(getContext().getCacheDir(), uri.getPath());
return ParcelFileDescriptor.open(privateFile, ParcelFileDescriptor.MODE_READ_ONLY);
}
清单:
<provider
android:name=".ShareContentProvider"
android:authorities="com.package.example"
android:grantUriPermissions="true"
android:exported="true">
</provider>
当打开邮件应用程序共享文件时,它说它无法附加文件,因为它只有 0 个字节。通过蓝牙共享它也失败了。但是我可以在 Content Provider 中读出privateFile,所以它存在并且有内容。有什么问题?
【问题讨论】:
-
是在您的自定义
ContentProvider中调用的query()方法吗? -
Yes 在 openFile 之前被调用了 3 次。第一个参数总是: content://com.package.example/file.txt
-
和投影/列是: _display_name 和 _size ?顺便说一句,为什么不使用
android.support.v4.content.FileProvider? -
是的,它们在第二个参数中。我只在搜索这个时找到了 ContentProvider。但我现在也要看看 FileProvider。
-
但如果您仍然想要自定义
ContentProvider,请参阅android.provider.OpenableColumns
标签: android android-contentprovider internal-storage share-intent android-internal-storage