有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Android摄像头QR扫描仪的java权限

我正在创建一个安卓应用程序,希望集成ZXing QR扫描仪。当我出于某种目的启动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 = 安卓.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= 安卓.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 安卓.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();
    }
}

共 (3) 个答案

  1. # 1 楼答案

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

  2. # 2 楼答案

    首先,您需要将摄像头权限添加到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;
             }
           }
        }
    
  3. # 3 楼答案

    在建立了你的相机源后,我也遇到了同样的问题。把这句话加到你的代码里,对我有用

    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);
    }