相机意图权限,android,为什么这不起作用?

Camera intent permission, android, Why this do not work?

对清单使用权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

代码

    mCameraButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (ActivityCompat.checkSelfPermission(getActivity(),
                    Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, 1000);
            } else {
                startCameraActivity();
            }
        }
    });

public void startCameraActivity() {
    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
        startActivityForResult(cameraIntent, 1000);
    }
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == 1000) {
            first_getUri = data.getData();
            Bitmap bitmap = null;
            try {
                bitmap = getBitmapFromUri(first_getUri);
            } catch (IOException e) {
            }

            File imageFile = null;
            try {
                imageFile = createFileFromBitmap(bitmap);
            } catch (IOException e) {
            }
            returnUri = Uri.fromFile(imageFile);
        }

        Glide.with(this)
                .load(returnUri)
                .override(1280, 1280)
                .into(mImageview);
    }
}

还有其他方法(可以忽略)

private Bitmap getBitmapFromUri(Uri uri) throws IOException {
    ParcelFileDescriptor parcelFileDescriptor =
            getActivity().getContentResolver().openFileDescriptor(uri, "r");
    FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();

    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inJustDecodeBounds = true;
    BitmapFactory.decodeFileDescriptor(fileDescriptor, null, opts);

    int width = opts.outWidth;
    int height = opts.outHeight;

    float sampleRatio = getSampleRatio(width, height);

    opts.inJustDecodeBounds = false;
    opts.inSampleSize = (int) sampleRatio;

    Bitmap resizedBitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, opts);
    Log.d("Resizing", "Resized Width / Height : " + resizedBitmap.getWidth() + "/" + resizedBitmap.getHeight());
    parcelFileDescriptor.close();
    return resizedBitmap;
}

private float getSampleRatio(int width, int height) {

    final int targetWidth = 1280;
    final int targetheight = 1280;

    float ratio;

    if (width > height) {
        // Landscape
        if (width > targetWidth) {
            ratio = (float) width / (float) targetWidth;
        } else ratio = 1f;
    } else {
        // Portrait
        if (height > targetheight) {
            ratio = (float) height / (float) targetheight;
        } else ratio = 1f;
    }
    return Math.round(ratio);
}

private File createFileFromBitmap(Bitmap bitmap) throws IOException {
    File newFile = new File(getActivity().getFilesDir(), makeImageFileName());
    FileOutputStream fileOutputStream = new FileOutputStream(newFile);
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
    fileOutputStream.close();
    return newFile;
}

private String makeImageFileName() {

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd_hhmmss");
    Date date = new Date();
    String strDate = simpleDateFormat.format(date);
    return strDate + ".png";
}

CODE 在 CODE 用于从图库中获取图像时运行良好

private void startGallery() {
    Intent cameraIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    cameraIntent.setType("image/*");
    if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
        startActivityForResult(cameraIntent, 2000);
    }
}

所以,我认为问题出在 android 权限上。

CODE 在 android 5.xx

下运行良好

但不要超过或等于 android 6.xx

问题:是否有任何权限失败的代码我错过了?

Android权限太难理解能告诉我怎么修改这个CODE吗?

编辑

不工作意味着:如果我点击 mCameraButton,什么也不会发生。什么也没发生。

So, i think problem is in android permission.

CODE works well under or equal android 5.xx

But do not works on over or equal android 6.xx

为此,您必须为 Android 6.0 及更高版本添加运行时权限。

示例。

final private int REQUEST_CODE_ASK_PERMISSIONS_CAMERA = 100;
final private int REQUEST_CODE_ASK_PERMISSIONS_EXTERNAL_STORAGE = 200;

// For Check Camera Permission
if (Build.VERSION.SDK_INT >= 23) {
            int hasPermission = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA);
            if (hasPermission != PackageManager.PERMISSION_GRANTED) {
                if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
                    // Display UI and wait for user interaction
                    getErrorDialog("You need to allow Camera permission." +
                            "\nIf you disable this permission, You will not able to add attachment.", getActivity(), true).show();
                } else {
                    requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_ASK_PERMISSIONS_CAMERA);
                }
                return;
            }
        }

// For Check Read External Permission.
if (Build.VERSION.SDK_INT >= 23) {
            int hasPermission = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE);
            if (hasPermission != PackageManager.PERMISSION_GRANTED) {
                if (shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    // Display UI and wait for user interaction
                    getErrorDialog("You need to allow Read External Storage permission." +
                            "\nIf you disable this permission, You will not able to add attachment.", getActivity(), false).show();
                } else {
                    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_ASK_PERMISSIONS_EXTERNAL_STORAGE);
                }
                return;
            }
        }

@Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_PERMISSIONS_CAMERA:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    Toast.makeText(getActivity(), "Permission Grant", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                    String imageFileName = "JPEG_" + timeStamp + ".jpg";
                    File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), imageFileName);
                    uri = Uri.fromFile(imageStorageDir);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                    startActivityForResult(intent, 1);

                } else {
                    // Permission Denied
                    Toast.makeText(getActivity(), "Required permission is disable.", Toast.LENGTH_SHORT).show();
                }
                break;

            case REQUEST_CODE_ASK_PERMISSIONS_EXTERNAL_STORAGE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    Toast.makeText(getActivity(), "Permission Grant", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(intent, 2);

                } else {
                    // Permission Denied
                    Toast.makeText(getActivity(), "Required permission is disable.", Toast.LENGTH_SHORT).show();
                }
                break;

            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

public AlertDialog.Builder getErrorDialog(String message, Context context, final boolean isFromCamera) {
        final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
        alertDialog.setTitle(getString(R.string.app_name)).setMessage(message);
        alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();
                if (Build.VERSION.SDK_INT >= 23) {
                    if(isFromCamera){
                        requestPermissions(new String[]{Manifest.permission.CAMERA},
                                REQUEST_CODE_ASK_PERMISSIONS_CAMERA);
                    }else {
                        requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                                REQUEST_CODE_ASK_PERMISSIONS_EXTERNAL_STORAGE);
                    }
                }

            }
        });
        return alertDialog;
    }

Android Marshmellow 开始,Android 生态系统要求开发人员在运行时获得某些权限,这意味着他们应该明确要求用户授予权限。您可以阅读更多 here

但我知道请求这些权限需要编写大量样板代码,这很快就会让人望而生畏。所以我建议你使用第三方库。我最喜欢的是 LetLet 大大减少了使用运行时权限所需的样板文件。

请求 运行-时间许可很容易理解。 请在 运行 时间查看 Android 官方请求权限。

Check it out here