android 7.0 調用系統相機崩潰的解決方案

項目運行兩個禮拜了,相機也在7.0以下運行的完美,突然早上同事拿他的7.0手機給我說 這是一個大bug.我一看調用相機直接崩潰。報的錯誤如下圖:


接着我以爲是我的文件路徑錯誤,找了老半天沒發現問題,仔細想想不太可能了。於是乎,開始求助各大網友了。

解決方案:

1、(推薦)7.0之後你的app就算有權限,給出一個URI之後手機也認爲你沒有權限。

不用修改原有代碼,在Application的oncreate方法中:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
    StrictMode.setVmPolicy(builder.build());
}

2、在調用相機的時候添加7.0系統的判斷,

/*獲取當前系統的android版本號*/
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Log.e("currentapiVersion","currentapiVersion====>"+currentapiVersion);
if (currentapiVersion<24){
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(pathFile));
    startActivityForResult(intent, TAKE_PICTURE);
}else {
    ContentValues contentValues = new ContentValues(1);
    contentValues.put(MediaStore.Images.Media.DATA, pathFile.getAbsolutePath());
    Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValues);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    startActivityForResult(intent, TAKE_PICTURE);
}

推薦使用第一種。

參考:https://developer.android.com/reference/android/support/v4/content/FileProvider.html


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章