android - 从我的应用程序打开的 PDF 文件无法共享
问题描述
在我的应用程序中,我从 url 下载 pdf 文件并使用选择器打开此 pdf。无法共享打开的文件。
这是我用来打开pdf文件的代码。
File file = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOWNLOADS).toString()+"/oferte/oferta"+insertedid+".pdf");
File(getApplicationContext().getFilesDir().toString()+"/oferta"+idfactura+".pdf");
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
startActivity(intent);
finish();
} catch (ActivityNotFoundException e) {
}
解决方案
第一个应用程序必须具有 READ_EXTERNAL_STORAGE 权限。运行时请求(Android 6.0 及更高版本)。链接https://developer.android.com/training/permissions/requesting.html
并且从android N 共享文件到其他app 必须使用FileProvider。</p>
编辑清单 xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<application
...>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${appPackageName}.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
...
</application>
</manifest>
res/xml/filepaths.xml
<paths>
<files-path path="files/" name="myfiles" />
</paths>
共享文件
Intent target = new Intent(Intent.ACTION_VIEW);
Uri fileUri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
fileUri = FileProvider.getUriForFile(this,
"appPackageName.fileprovider", file);
target.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
target.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
} else {
fileUri = Uri.fromFile(file);
}
target.setDataAndType(fileUri,"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
startActivity(intent);
finish();
} catch (ActivityNotFoundException e) {
}
链接https://developer.android.com/training/secure-file-sharing/setup-sharing https://stackoverflow.com/a/38858040/4696538
推荐阅读
- c# - 复制流和 ReadToEndAsync()
- r - 如何通过引用提供现有变量进行变异?
- excel - excel vba Internet Explorer 自动化 - 访问两个 div 内的输入
- sql-server - 插入后实体框架更新为错误的值
- java - 为什么我可以像原语一样测试包装器的不等式?我可以为我创建的课程做这件事吗?
- python - Namedtuple 是用详细的类型名实现的
- javascript - JQuery 在 div 内滚动
- python - 从两个数组创建 numpy 数组,以便备用索引包含来自不同数组的元素
- haskell - 流式库中 takeWhileM 函数的一元谓词
- c# - 1 次登录尝试失败后服务器锁定用户名?