更改意图前,请先征得相机许可

时间:2018-08-01 09:25:56

标签: java android

我想在更改活动之前提示用户相机权限。如果用户允许,它将进入QR码扫描器,如果用户拒绝,它将返回同一屏幕。

这是我现在拥有的

new

1 个答案:

答案 0 :(得分:1)

这是您可以做的,首先请求权限

 ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{Manifest.permission.CAMERA},
                1);

现在检查是否允许该权限

@Override
public void onRequestPermissionsResult(int requestCode,
                                   String permissions[], int[] grantResults) {
switch (requestCode) {
    case 1: {

      // If request is cancelled, the result arrays are empty.
      if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Intent intent = new Intent(BaseMapActivity.this, BarCodeReaderActivity.class);
            startActivityForResult(intent, ITEM_LOCATION_REQUEST);
            // permission was granted, yay! Do the
            // camera-related task you need to do.          
        } else {

            // permission denied, boo! Disable the
            // functionality that depends on this permission.
            Toast.makeText(MainActivity.this, "Permission denied for camera", Toast.LENGTH_SHORT).show();
        }
        return;
    }

    // other 'case' lines to check for other
    // permissions this app might request
 }
}

希望这会有所帮助