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

时间:2016-11-07 13:21:38

标签: android android-permissions

在清单上使用权限

<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"/>

CODE

    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上运行

问题:我错过了CODE的许可吗?

Android权限太难理解您是否会告诉我如何修改此代码?

修改

不工作意味着:如果我点击mCameraButton,不要发生任何事情。什么也没发生。

3 个答案:

答案 0 :(得分:2)

  

所以,我认为问题是在Android许可中。

     

CODE在android 5.xx

之下运行良好      

但是不能在超过或等于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;
    }

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

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

Check it out here