【问题标题】:Permissions for Android Camera QR ScannerAndroid 相机 QR 扫描仪的权限
【发布时间】:2019-01-06 12:37:25
【问题描述】:

我正在创建一个 android 应用程序并想集成 ZXing QR Scanner。当我从 Intent 启动 QRScanner 活动时,我收到吐司说“权限被拒绝,您无法访问和摄像头”,并且应用程序冻结而不是请求摄像头权限。

对于如何正确实施权限请求或识别我查看的任何错误的任何帮助将不胜感激。

      public class Qrscanner extends AppCompatActivity implements 
      ZXingScannerView.ResultHandler {

    private static final int REQUEST_CAMERA = 1;
    private ZXingScannerView scannerView;
    private static int camId = Camera.CameraInfo.CAMERA_FACING_BACK;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        scannerView = new ZXingScannerView(this);
        setContentView(scannerView);
        int currentApiVersion = Build.VERSION.SDK_INT;

        if(currentApiVersion >=  Build.VERSION_CODES.M)
        {
            if(checkPermission())
            {
                Toast.makeText(getApplicationContext(), "Permission already granted!", Toast.LENGTH_LONG).show();
            }
            else
            {
                requestPermission();
            }
        }
    }

    private boolean checkPermission()
    {
        return (ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA) == PackageManager.PERMISSION_GRANTED);
    }

    private void requestPermission()
    {
        ActivityCompat.requestPermissions(this, new String[]{CAMERA}, REQUEST_CAMERA);
    }

    @Override
    public void onResume() {
        super.onResume();

        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
            if (checkPermission()) {
                if(scannerView == null) {
                    scannerView = new ZXingScannerView(this);
                    setContentView(scannerView);
                }
                scannerView.setResultHandler(this);
                scannerView.startCamera();
            } else {
                requestPermission();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        scannerView.stopCamera();
    }

    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        final int req = requestCode;
        switch (requestCode) {

            case REQUEST_CAMERA:
                if (grantResults.length > 0) {

                    boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    if (cameraAccepted){
                        Toast.makeText(getApplicationContext(), "Permission Granted, Now you can access camera", Toast.LENGTH_LONG).show();
                    }else {
                        Toast.makeText(getApplicationContext(), "Permission Denied, You cannot access and camera", Toast.LENGTH_LONG).show();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            if (shouldShowRequestPermissionRationale(CAMERA)) {
                                showMessageOKCancel("You need to allow access to both the permissions",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  //                                                    
   requestPermissions(new String[]{CAMERA},
   //                                                            
   REQUEST_CAMERA);

    ActivityCompat.requestPermissions(getParent(), new String[] 
    {Manifest.permission.CAMERA}, req);

                                                }
                                            }
                                        });
                                return;
                            }
                        }
                    }
                }
                break;
        }
    }

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new android.support.v7.app.AlertDialog.Builder(Qrscanner.this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    }

    @Override
    public void handleResult(final Result result) {
        final String myResult = result.getText();
        Log.d("QRCodeScanner", result.getText());
        Log.d("QRCodeScanner", result.getBarcodeFormat().toString());

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Scan Result");
        builder.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                scannerView.resumeCameraPreview(Qrscanner.this);
            }
        });
        builder.setNeutralButton("Confirm", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
               Intent intent = new Intent(getApplicationContext(),AddKeys.class);
               intent.putExtra("publicKey",result.getText());
               startActivity(intent);
            }
        });
        builder.setMessage(result.getText());
        AlertDialog alert1 = builder.create();
        alert1.show();
    }
}

【问题讨论】:

    标签: java android android-studio qr-code zxing


    【解决方案1】:

    首先您需要将相机权限添加到您的AndroidManifest.xml

    <uses-permission android:name="android.permission.CAMERA"/>
    

    然后您需要在运行时要求用户启用此权限:

    activity.requestPermissions(new String[]{Manifest.permission.CAMERA}, 1011);
    

    然后重写权限对话结果后将调用的方法:

        @Override
        public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1011: {
    
          // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    
                // Here user granted the permission     
                } else {
    
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                    Toast.makeText(MainActivity.this, "Permission denied to read your Camera", Toast.LENGTH_SHORT).show();
                }
                return;
             }
           }
        }
    

    【讨论】:

    • 启动条码扫描器活动并返回上一个活动后,应用变得非常缓慢并崩溃,您知道这是为什么吗?
    • 请在您的问题中发布日志
    【解决方案2】:

    您的问题有一个非常简单的解决方案。在onCreate 里面提供运行时权限。我建议您使用 dexter 库,因为它是实现运行时权限的最简单方法。这是图书馆的链接: https://github.com/Karumi/Dexter

    【讨论】:

      【解决方案3】:

      在构建您的 cameSource 后,我遇到了同样的问题。将此行添加到您的代码中,它适用于我

      final String[] permissions = new String[] Manifest.permission.CAMERA};
      
      if (!ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.CAMERA)) {
          ActivityCompat.requestPermissions(MainActivity.this, permissions, RC_HANDLE_CAMERA_PERM);
      }
      

      【讨论】:

        猜你喜欢
        • 2018-06-17
        • 2021-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-13
        相关资源
        最近更新 更多