android 7.0 打開相機 以及路徑uri 權限問題 解決

  1. 在AndroidManifest文件的application標籤下添加如下內容:
<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="你的包名.fileProvider"
    android:grantUriPermissions="true"
    android:exported="false">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>
  1. 2.在res目錄下新建xml資源目錄,並新建file_paths文件:
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <!--
        path:需要臨時授權訪問的路徑(.代表所有路徑)
        name:就是你給這個訪問路徑起個名字
    -->
    <external-path path="." name="external_storage_root" />
</paths>
  1. 打開相機拍照方法
 /**
     * 打開相機拍照
     *
     * @param activity
     * @return
     */
    public void openCamera(Activity activity) {

        String filename = new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.CHINA)
                .format(new Date()) + ".png";
        File pictureFile = new File(getPhotoPath());

        Intent mIntent = new Intent();
        mIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

            Uri contentUri = FileProvider.getUriForFile(activity, "com.zhijiuling.zhonghua.zhdj.fileProvider", pictureFile);
            //拍照結果輸出到這個uri對應的file中
            mIntent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
            //對這個uri進行授權
            mIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            //拍照結果輸出到這個uri對應的file中
            mIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(pictureFile));
        }

        mIntent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
        activity.startActivityForResult(mIntent, PHOTO_SETRESULT_CODE);
    }

    // 拍照路徑
    public String getPhotoPath() {
        File file = new File(Environment.getExternalStorageDirectory(), "/imgs");
        if (!file.exists()) {
            file.mkdirs();
        }
        String path = file.getPath() + "photo.jpg";
        return path;
    }

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