【发布时间】:2019-07-24 06:42:47
【问题描述】:
我无法使用 Android N 打开外部存储中的文件。
文件路径
file:///storage/emulated/0/Download/SamplePDFFile_5mb.pdf
初步实施 完美适用于低于 7 的 Android 版本
File file = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "SamplePDFFile_5mb.pdf");
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
相同的实现不适用于 7,但有以下例外。
android.os.FileUriExposedException
所以我发现了类似的问题并关注this,以便将应用程序定位的新安卓安全功能修复为 24 或更高。
新实施
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "SamplePDFFile_5mb.pdf");
//old way
//Uri uri = Uri.fromFile(file);
//new way
Uri uri = FileProvider.getUriForFile(MainActivity.this, getPackageName() + ".provider", file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
provider_paths.xml
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
AndroidManifest.xml
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
即使在 Android Manifest、provider_paths.xml 和 FileProvider 中添加了必需的标签后,我也无法打开该文件。打开活动自行关闭。logcat 中没有错误或消息。
【问题讨论】:
标签: android android-intent android-external-storage android-fileprovider