Android 相册选择照片或拍照获取图片系统6.0及7.0实现

6.0及6.0以上权限动态询问

 private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 6;
 private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE2 = 7;

 //手机拍照
        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(getApplicationContext(),
                        Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(ReviewActivity.this,
                            new String[]{Manifest.permission.CAMERA},
                            MY_PERMISSIONS_REQUEST_CALL_PHONE);
                } else {
                    photo();
                    dialog.dismiss();
                }
            }
        });



 //从相册选择图片
        photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(getApplicationContext(),
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(ReviewActivity.this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            MY_PERMISSIONS_REQUEST_CALL_PHONE2);

                } else {
                    int selectedMode;
                    selectedMode = MultiImageSelectorActivity.MODE_MULTI;
                    int maxNum = 9 - drr.size();
                    Intent intent = new Intent(ReviewActivity.this,                             MultiImageSelectorActivity.class); 
                    // 是否显示拍摄图片
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, false);
                    // 最大可选择图片数量
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, maxNum);
                    // 选择模式
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, selectedMode);

                    startActivityForResult(intent, RESULT_LOAD_IMAGE);
                    dialog.dismiss();
                }

            }
        });


 /**
     * 拍照方法代码
     */
    public void photo() {
        try {
            if (hasSdcard()) {
                String sdcardState = Environment.getExternalStorageState();
                String sdcardPathDir = Environment.getExternalStorageDirectory().getPath() + "/tempImage/";
                File file = null;

                if (Environment.MEDIA_MOUNTED.equals(sdcardState)) {
                    // 有sd卡,是否有myImage文件夹
                    File fileDir = new File(sdcardPathDir);
                    if (!fileDir.exists()) {
                        fileDir.mkdirs();
                    }
                    // 是否有headImg文件
                    file = new File(sdcardPathDir + System.currentTimeMillis() + ".JPEG");
                }
                if (file != null) {
                    path = file.getPath();
                    photoUri = Uri.fromFile(file);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        //通过FileProvider创建一个content类型的Uri
                        photoUri = FileProvider.getUriForFile(ReviewActivity.this, "com.zuihou.drunkenmonkey.fileprovider", file);
                    }
                    Intent openCameraIntent = new Intent();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        openCameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
                    }
                    openCameraIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                    openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                    startActivityForResult(openCameraIntent, TAKE_PICTURE);
                }
            } else {
                ToastUtil.showToast(getApplicationContext(), "设备没有SD卡!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }

这里有一句代码:

FileProvider.getUriForFile(ReviewActivity.this, "com.zuihou.drunkenmonkey.fileprovider", file);

在用Android 7.0版本时,调用相机拍照出现了异常 FileUriExposedException,就是在传递uri时出错 Android 7.0后又修改了文件权限,可以使用FileProvider解决

在项目res目录下创建xml文件夹

<?xml version="1.0" encoding="utf-8"?>
<paths>
<!--        xml文件是唯一设置分享的目录 ,不能用代码设置

         1.<files-path>        getFilesDir()  /data/data//files目录
         2.<cache-path>        getCacheDir()  /data/data//cache目录

         3.<external-path>     Environment.getExternalStorageDirectory()

         SDCard/Android/data/你的应用的包名/files/ 目录
         4.<external-files-path>     Context#getExternalFilesDir(String) Context.getExternalFilesDir(null).
         5.<external-cache-path>      Context.getExternalCacheDir().
     -->

    <!--    path :代表设置的目录下一级目录 eg:<external-path path="images/"
                整个目录为Environment.getExternalStorageDirectory()+"/images/"
            name: 代表定义在Content中的字段 eg:name = "myimages" ,并且请求的内容的文件名为default_image.jpg
                则 返回一个URI   content://com.example.myapp.fileprovider/myimages/default_image.jpg
    -->


    <!--当path 为空时 5个全配置就可以解决-->


    <external-path
        name="camera_photos"
        path="" />
</paths>

在manifest.xml文件添加provider,相机,读写文件权限

  <provider
            android:name="android.support.v4.content.FileProvider"   //固定值
            android:authorities="com.zuihou.drunkenmonkey.fileprovider"  //前面为项目的包名,fileprovider固定
            android:exported="false" //是否支持其它应用调用当前组件 ,要求为flase
            android:grantUriPermissions="true">  
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS" //固定值
                android:resource="@xml/file_paths" /> //在res目录下定义的filepaths.xml文件,名字可以自定义
        </provider>
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

获取权限后返回结果代码

 @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                photo();
            } else {
                // Permission Denied
                ToastUtil.showToast(ReviewActivity.this, "Permission Denied");
            }
        }

        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE2) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                int selectedMode;
                selectedMode = MultiImageSelectorActivity.MODE_MULTI;
                int maxNum = 9 - drr.size();
                Intent intent = new Intent(ReviewActivity.this, MultiImageSelectorActivity.class);
                // 是否显示拍摄图片
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, false);
                // 最大可选择图片数量
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, maxNum);
                // 选择模式
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, selectedMode);

                startActivityForResult(intent, RESULT_LOAD_IMAGE);

                dialog.dismiss();
            } else {
                // Permission Denied
                ToastUtil.showToast(ReviewActivity.this, "Permission Denied");
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页