看着例子挺简单的 到真机玩一圈就得添油加醋了
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 支持吧
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.