看着例子挺简单的 到真机玩一圈就得添油加醋了
Intent intent = new Intent("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Uri uri Uri.fromFile(file); intent.setDataAndType(uri, "application/pdf"); return Intent.createChooser(intent, "Open File");
真敢用这段代码 上生产就等着被报障给烦死吧
添油加醋版:
Intent intent = new Intent(Intent.ACTION_VIEW); intent.addCategory(Intent.CATEGORY_DEFAULT);
Uri uri; //7.0 兼容 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { uri = FileProvider.getUriForFile(context, "你的 pdf 文件本地路径", 你的 pdf 文件); try { context.grantUriPermission(BuildConfig.APPLICATION_ID, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); } catch (Exception e) { } // 判断版本大于等于 7.0 StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build()); } else { uri = Uri.fromFile(你的 pdf 文件); } intent.setDataAndType(uri, FILE_TYPE); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { context.startActivity(intent); //打开文件给第三方使用 成功 } catch (Exception e) { //打开文件失败 }
定义一个 provider
<provider android:name="android.support.v4.content.FileProvider" android:authorities="你的包名.fileprovider" android:grantUriPermissiOns="true" android:exported="false"> <!--元数据--> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/你的 xml 配置文件" /> </provider>
创建你的 xml 配置文件
<resources> <paths> <external-path name="download" path=""> <root-path name="root" path="" /> <files-path name="files" path="" /> <cache-path name="cache" path="" /> <external-path name="external" path="" /> <external-path name="files_root" path="Android/data/你的包名 /"/> <external-path name="external_storage_root" path="."/> <external-files-path name="external_file_path" path="" /> <external-cache-path name="external_cache_path" path="" /> </paths>
</external-path></paths></resources> 讲道理能给的 给齐了 亲测 WPS office, Microsoft Word 安装后第一次打开都会说 我读不到你,第二次就读到了... 多看阅读 pdf 里太小的字体可能会变成黑条 其他的没发现有问题
ios webview 能直接读取 等 Android 支持吧
1 bertsir 2019-05-08 16:09:31 +08:00 X5 内核解君愁 |
![]() | 2 Sasasu 2019-05-08 16:39:48 +08:00 你这不能叫 "7.0 兼容",这叫 "修复在 7.0 下因没有申请权限导致崩溃的问题" |
![]() | 3 lucher 2019-05-20 14:24:40 +08:00 Android 7.0 的新特性,应用间分享文件需要用 FileProvider,你看的示例代码太老了 |
![]() | 4 kingiis OP 开启严苛模式 |
![]() | 5 kingiis OP @Sasasu 顶哦 管用就行 StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build()); |