1. 程式人生 > >Android 7.0相機適配許可權管理

Android 7.0相機適配許可權管理

剛從6.0的坑中跳出,又跳進了7.0的漩渦中。表示心累,但又不得不去學習學習新的知識,新增新的程式碼。

今天就和大家聊一聊我遇見的一些問題和解決的方法,先貼圖。
錯誤日誌

剛開始的時候,看到這個錯的我是一臉的懵逼 -_- ,又是在網上看資料,又是翻牆的,但最後發現解決這個問題很簡單,就只需要新增一點點東西就OK了,給大家解釋下這個錯是什麼意思,就是對於面向 Android N 的應用,Android 框架執行的 StrictMode,API 禁止向您的應用外公開 file://URI。 如果一項包含檔案 URI 的 Intent 離開您的應用,應用失敗,並出現 FileUriExposedException異常。若要在應用間共享檔案,您應傳送一項 content://URI,並授予 URI 臨時訪問許可權。 進行此授權的最簡單方式是使用 FileProvider類。 下面就給各位看官始貼程式碼了。

1、在AndroidManifest中新增程式碼

<application
        android:name=".AppAplication"
        android:allowBackup="true"
        android:icon="@mipmap/icon_log"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme_Animation_Activity_RightInRightOut"
>
//主要的還是下面的這個 <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/filepaths"></meta-data> </application>

2、建立一個XML檔案,編寫filepaths.xml檔案
一個FileProvider只能生成一個content URI 對應你事先指定目錄下的檔案。對於指定一個目錄,使用元素的子元素,在XML中指定它的儲存區域和路徑。例如,下面的paths元素告訴FileProvider你打算請求你的私有檔案區域的 images/ 子目錄的content URIs

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="名字" path="Android/data/包名/檔名/" />
    <external-path name="名字" path="image/" />
</paths>

3、現在就可以再相機拍照的地方新增下面的程式碼了

/**
 * 7.0 拍照許可權
 * 我是直接提取成一個方法了
 */
public void getPicturesFile(int code){
final File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/檔名/" + System.currentTimeMillis() + ".jpg");
        try {
            file.getParentFile().mkdirs();
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mTmpPath = file.getAbsolutePath();
        final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
        //判斷一下當前的系統版本,然後在分配許可權
        if (Build.VERSION.SDK_INT >= 24) {
            //Android 7.0許可權申請
            ContentValues contentValues = new ContentValues(1);
            contentValues.put(MediaStore.Images.Media.DATA, mTmpPath);
            Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, code);
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mTmpPath)));
            startActivityForResult(intent, code);
        }
    }