美文网首页
解决Android无法启动系统播放本地视频问题

解决Android无法启动系统播放本地视频问题

作者: 张大川大川 | 来源:发表于2018-04-24 21:56 被阅读85次

旧的解决方案

从各种博客上都会搜到这样的答案:

    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中创建一个xml/provider_paths.xml文件,内容如下

<?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了。

最终结论

刚开始没有加read_uri_permission的flag,调用不起来。最终代码:

  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);

亲测可用

相关文章

网友评论

      本文标题:解决Android无法启动系统播放本地视频问题

      本文链接:https://www.haomeiwen.com/subject/shsslftx.html