Android调用外部应用打开文件

您所在的位置:网站首页 安卓手机用其它应用打开怎么添加应用锁 Android调用外部应用打开文件

Android调用外部应用打开文件

2024-07-11 18:15| 来源: 网络整理| 查看: 265

try { Uri path; Intent intent = new Intent(Intent.ACTION_VIEW); if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.N){ path = FileProvider.getUriForFile(this, "manifest文件下的provider", file); }else { path = Uri.fromFile(file); } //注意intent用addFlags 如果intent在这行代码下使用setFlags会导致其他应用没有权限打开你的文件 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); String type=getMimeType(file); intent.setDataAndType(path, type); //如果想让用户每次打开文件都自己选择(方便切换应用打开)加上下面这句代码 //intent=Intent.createChooser(intent, "请选择打开此文件的应用") startActivity(intent); }catch (ActivityNotFoundException e){ sendToastMessage("此设备没有可以打开此文件的软件"); }

注意setFlags的调用建议使用addFlags

在manifests文件下创建provider注意authorities的值xml值要和代码中相同

xml下的file_paths文件根据自己的需要进行配置

获取文件的MIME注意不要用后缀名

public static String getMimeType(File file) { String extension = getFileExtension(file.getName()); if (extension != null) { MimeTypeMap mime = MimeTypeMap.getSingleton(); return mime.getMimeTypeFromExtension(extension); } return null; } public static String getFileExtension(String fileName) { int dotIndex = fileName.lastIndexOf('.'); if (dotIndex < 0) { return null; } return fileName.substring(dotIndex + 1); }



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3