1. 程式人生 > >Android7.0及以上開啟相機閃退,startActivityForResult報錯解決

Android7.0及以上開啟相機閃退,startActivityForResult報錯解決

這個問題出現的原因主要是由於在Android 7.0以後,用了Content Uri 替換了原本的File Uri,故在targetSdkVersion=24的時候,部分 “`Uri.fromFile()“` 方法就不適用了。 **File Uri 與 Content Uri 的區別** - File Uri 對應的是檔案本身的儲存路徑 - Content Uri 對應的是檔案在Content Provider的路徑 所以在android 7.0 以上,我們就需要將File Uri轉換為 Content Uri。具體轉換方法如下:(需要使用的時候直接複製貼上即可)

 /**
     * 轉換 content:// uri
     *
     * @param imageFile
     * @return
     */
    public Uri getImageContentUri(File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Images.Media._ID },
                MediaStore.Images.Media.DATA + "=? ",
                new String[] { filePath }, null);

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

主要程式碼就是這樣,下面寫一個完整的調取系統相機的程式碼:

   File outputImage = new File(ct.getSDPath() + "/bhne/export/" + projectpath + "/", java.util.UUID.randomUUID().toString() + ".jpg");
                                pathImage = outputImage.toString();
                                try {
                                    if (outputImage.exists()) {
                                        outputImage.delete();
                                    }
                                    outputImage.createNewFile();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                                Intent intentPhoto = new Intent("android.media.action.IMAGE_CAPTURE"); //拍照
                                //Uri imageUri = Uri.fromFile(outputImage);//7.0之前的寫法
                                Uri imageUri = getImageContentUri(outputImage);//直接呼叫咱們上面寫好的方法
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                                    intentPhoto.putExtra(MediaStore.EXTRA_OUTPUT,
                                            FileProvider.getUriForFile(PictureActivity.this,"bhne.com.wlprojectapplication.fileprovider", outputImage));
                                }else {
                                    intentPhoto.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outputImage));
                                }






                                intentPhoto.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                                startActivityForResult(intentPhoto, 3);
  Uri imageUri = getImageContentUri(outputImage);//直接呼叫咱們上面寫好的方法

主要就是這一行程式碼,呼叫了上面所寫的程式碼,還需注意的是需要在許可權中宣告一下:

 <application
        ...>


        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="bhne.com.wlprojectapplication.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"></meta-data>
        </provider>

然後在res檔案下建立一個xml資料夾,在資料夾下建立新的xml檔案,名字為file_paths:


<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>
基本上就是這樣,以後希望長點記性。