android 适配8.0。6.0调起手机拍照获取照片路径

 用的时候直接复制即可 必要的已经写上备注,欢迎大神指点,有些代码是拼凑的,然后我自己的总结。

首先先配置:

在清单文件配置一下

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="(你的包名).fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths">meta-data>
provider>

在rec文件下创建xml文件夹,在里面创建xml文件

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
paths>
java代码如下:
/**
     * 使用相机
     */
    private void useCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/test/" + System.currentTimeMillis() + ".jpg");
        file.getParentFile().mkdirs();

        //改变Uri  com.xykj.customview.fileprovider注意和xml中的一致
        Uri uri = FileProvider.getUriForFile(this, "com.example.administrator.myapplication.fileprovider", file);
        //添加权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, REQUEST_CAMERA);
    }
    public void applyWritePermission() {

        String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};

        if (Build.VERSION.SDK_INT >= 23) {
            int check = ContextCompat.checkSelfPermission(this, permissions[0]);
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (check == PackageManager.PERMISSION_GRANTED) {
                //调用相机
                useCamera();
            } else {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        } else {
            useCamera();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            useCamera();
        } else {
            // 没有获取 到权限,从新请求,或者关闭app
            Toast.makeText(this, "需要存储权限", Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
//            Log.e("TAG", "---------" + FileProvider.getUriForFile(this, "com.xykj.customview.fileprovider", file));
            //在手机相册中显示刚拍摄的图片
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri contentUri = Uri.fromFile(file);
                String path = contentUri.getPath();
                Log.e("TAGSSSSSSSSS", contentUri.toString());
                //文件的路径
                String absolutePath = file.getAbsolutePath();
                //文件的名字
                String parent = file.getName();
                Log.e("TAGQQQQQQQQQ", parent + "===" + absolutePath);
                mediaScanIntent.setData(contentUri);
                sendBroadcast(mediaScanIntent);
                //设置图片
                picture.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
            }else{
                File photoFile = new File(photoPath);
                if (photoFile.exists()) {
                    //通过图片地址将图片加载到bitmap里面
                    Bitmap bm = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
                    //将拍摄的照片显示到界面上
                    //这是返回来的路径
//                    results.confirm(pathsa);
                    Toast.makeText(MainActivity.this, "通过", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(MainActivity.this, "图片文件不存在", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    /**
     * 拍照的,照片路径
     */
    public void jsPath() {
        //获取SD卡安装状态
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {

            //设置图片保存路径
            photoPath = SAVED_IMAGE_PATH + "/" + System.currentTimeMillis() + ".png";

            File imageDir = new File(photoPath);
            if (!imageDir.exists()) {
                try {
                    //根据一个 文件地址生成一个新的文件用来存照片
                    imageDir.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            takePhotoByMethod1();
        } else {
            Toast.makeText(MainActivity.this, "SD卡未插入", Toast.LENGTH_SHORT).show();
        }
    }
    private void takePhotoByMethod1() {
        //实例化intent,指向摄像头
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //根据路径实例化图片文件
        File photoFile = new File(photoPath);
        //设置拍照后图片保存到文件中
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
        //启动拍照activity并获取返回数据
        startActivityForResult(intent, REQUEST_CAMERA);
    }
上面的是必要的执行代码。

下边:

switch (v.getId()) {
    case R.id.take_photo:
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            applyWritePermission();
        }else{
            jsPath();
        }
        break;
}

点击这个按钮就可以实现, 新手第一 次写 请多多指教。

你可能感兴趣的:(andorid)