解決Android無法啟動(dòng)系統(tǒng)播放本地視頻問題

舊的解決方案

從各種博客上都會(huì)搜到這樣的答案:

    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以及以上的手機(jī)就是拋出FileUriExposedException的異常。因此需要對(duì)uri進(jìn)行處理。

獲取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)建一個(gè)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);

親測可用

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,781評(píng)論 25 709
  • 文章內(nèi)容轉(zhuǎn)載自Android 7.0 行為變更 通過FileProvider在應(yīng)用間共享文件吧 - CSDN博客 ...
    暴躁的西瓜閱讀 2,429評(píng)論 0 3
  • Android7.0發(fā)布已經(jīng)有一個(gè)多月了,Android7.0在給用戶帶來一些新的特性的同時(shí),也給開發(fā)者帶來了新的...
    善良的老農(nóng)閱讀 828評(píng)論 0 5
  • 驚回夢(mèng),碧水涓,銀燭金盞,星火闌珊;風(fēng)塵漸,如絲怨,玉戶珠簾,翡波瀲滟。千年絲竹弦動(dòng)扇,一夕浸沒水潮殘。神女長鎖黃...
    夢(mèng)飲千樽月閱讀 650評(píng)論 0 49
  • 五律·賀蘭渝鐵路通車 龐學(xué)先 千山笑顏綻,萬水碧濤翻。 諧和越溪澗,移時(shí)到蜀園。 晨醒金市夢(mèng),夕至錦城喧。 雖在人...
    碌坪人閱讀 209評(píng)論 0 0

友情鏈接更多精彩內(nèi)容