踩了很多坑,最后总结出来的代码如下:
当你拥有文档的file路径时,使用以下工具类打开:
public static void openFile(Context context, File file){
ToastUtil.showMessage("打开文档中");
Intent intent = new Intent(Intent.ACTION_VIEW);
//intent.addCategory(Intent.CATEGORY_DEFAULT);
Uri uriForFile;
if (Build.VERSION.SDK_INT > 23){
//Android 7.0之后
uriForFile = FileProvider.getUriForFile(context, "com.example.wpsstudy.fileProvider", file);
// intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);//给目标文件临时授权
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//给目标文件临时授权
}else {
uriForFile = Uri.fromFile(file);
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//系统会检查当前所有已创建的Task中是否有该要启动的Activity的Task;
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setClassName(WpsModel.PackageName.NORMAL,WpsModel.ClassName.NORMAL);
// 若有,则在该Task上创建Activity;若没有则新建具有该Activity属性的Task,并在该新建的Task上创建Activity。
intent.setDataAndType(uriForFile,getMimeTypeFromFile(file));
Bundle bundle = new Bundle();
bundle.putString(WpsModel.OPEN_MODE, WpsModel.OpenMode.NORMAL); // 打开模式
bundle.putString(WpsModel.THIRD_PACKAGE, WpsModel.PackageName.NORMAL); // 第三方应用的包名,用于对改应用合法性的验证
intent.putExtras(bundle);