安卓7.0拍照遇到 Uri暴露錯誤

來源:互聯網
上載者:User

標籤:開始   one   src   xml檔案   pos   blank   etc   iss   ted   

最近,項目又做到,調用網路攝影機拍照擷取圖片這個功能。

用以前的代碼直接用,發現在Android7.0上使用時會出現問題。

Android6.0之後,動態申請許可權已成常態。

調用網路攝影機拍照擷取圖片這個功能,需要動態申請 照相機許可權、SD卡讀寫權限。

可是加了這些許可權後,還是會報錯。

錯誤:android.os.FileUriExposedException: file:///storage/emulated.. exposed beyond app through Intent.getData()

這個是uri暴露錯誤。

從Android 7.0開始,一個應用提供自身檔案給其它應用使用時,如果給出一個file://格式的URI的話,應用會拋出FileUriExposedException。這是由於Google認為目標app可能不具有檔案許可權,會造成潛在的問題。所以讓這一行為快速失敗。

網上有兩種解決方案:FileProvider方式 和 VmPolicy方式。

第一種是是Google官方推薦的解決方案,我這裡也是採用第一種方法。

步驟:1.在AndroidManifest.xml中添加如下代碼

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="">    <application        >                <provider            android:name="android.support.v4.content.FileProvider"            android:authorities="${applicationId}.provider"            android:exported="false"            android:grantUriPermissions="true">            <meta-data                android:name="android.support.FILE_PROVIDER_PATHS"                android:resource="@xml/provider_paths"/>        </provider>    </application></manifest>
View Code

        2.在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>
View Code

        3.使用到uri的代碼

Uri photoURI = Uri.fromFile(createImageFile());變成:Uri photoURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", createImageFile());
View Code

修改代碼後,再次調試,程式正常運行。

 

ps:只是個小功能,網上也有不少資料,但還是自己總結一下比較好!

 

安卓7.0拍照遇到 Uri暴露錯誤

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.