How to ask runtime permissions for Camera in Android , Runtime storage permissions

后端 未结 6 995
迷失自我
迷失自我 2020-12-01 16:47

I am doing an application to scan barcodes on a button click and it was working fine up to Lollipop versions. When I came to Marshmallow it stopped working. This is the erro

6条回答
  •  [愿得一人]
    2020-12-01 17:03

    This might help:

    if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
    {
        if(ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.CAMERA))
        {
            AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
            alertBuilder.setCancelable(true);
            alertBuilder.setTitle("Permission necessary");
            alertBuilder.setMessage("CAMERA is necessary");
            alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                public void onClick(DialogInterface dialog, int which) {
                    ActivityCompat.requestPermissions((Activity) context, 
                    new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUESTS);
                }
            });
            AlertDialog alert = alertBuilder.create();
            alert.show();
        } else {
            ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUESTS);
        }
        return false;
    } else {
        return true;
    }
    

    Where MY_PERMISSIONS_REQUESTS is your final value of the request code.

    It works just fine for me.

提交回复
热议问题