舊的解決方案
從各種博客上都會搜到這樣的答案:
Intent intent = new Intent(Intent.ACTION_VIEW);
String type = "video/*";
Uri name = Uri.fromFile(new File(path));
intent.setDataAndType(name, type);
startActivity(intent);
在android7.0以下這么做是沒有問題的吉挣。但是在android7.0以及以上的手機就是拋出FileUriExposedException的異常鲫趁。因此需要對uri進行處理顶燕。
獲取FileUri
google提供了FileProvider秩仆,使用它可以生成content://Uri來替代file://Uri
官方介紹:https://developer.android.com/reference/android/support/v4/content/FileProvider.html
Androidmainfest文件中添加Provider
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="包名.file-provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
res中創(chuàng)建一個xml/provider_paths.xml文件扁眯,內(nèi)容如下
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
這樣就可以用
FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID +
".file-provider", new File(vo.getActualPath());
來獲取uri了篮洁。
最終結(jié)論
剛開始沒有加read_uri_permission的flag绕德,調(diào)用不起來。最終代碼:
Uri uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID +
".file-provider", new File(vo.getActualPath()));
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(uri, "video/*");
getActivity().startActivity(intent);
親測可用