L3n*_*n95 1 android android-contentprovider internal-storage share-intent android-internal-storage
我正在内部存储上保存文件.它只是一个.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();
Run Code Online (Sandbox Code Playgroud)
然后我创建一个"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)));
Run Code Online (Sandbox Code Playgroud)
所选应用程序现在需要访问私有文件,因此我创建了一个内容提供程序.我刚刚更改了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);
}
Run Code Online (Sandbox Code Playgroud)
清单:
<provider
android:name=".ShareContentProvider"
android:authorities="com.package.example"
android:grantUriPermissions="true"
android:exported="true">
</provider>
Run Code Online (Sandbox Code Playgroud)
打开邮件应用程序以共享它所说的文件时,它无法附加文件,因为它只有0字节.通过蓝牙共享它也失败了.但是我可以privateFile在内容提供商中读出它,因此它存在且具有内容.问题是什么?
谢谢你的pskink.FileProvider工作得很好:
Gradle依赖:
compile 'com.android.support:support-v4:25.0.0'
表现:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.package.example"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
Run Code Online (Sandbox Code Playgroud)
XML文件夹中的file_paths.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<cache-path name="cache" path="/" />
</paths>
Run Code Online (Sandbox Code Playgroud)
分享意图:
File file = new File(context.getCacheDir(), filename);
Uri contentUri = FileProvider.getUriForFile(context, "com.package.example", file);
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
shareIntent.setType("text/plain");
context.startActivity(Intent.createChooser(shareIntent, context.getResources().getText(R.string.chooser)));
Run Code Online (Sandbox Code Playgroud)