LearnHouse

[Android]6.0使用camera出現Fail to connect to camera service

MANIFEST PERMISSIONS WON'T WORK on Android 6.0

Failed to open camera
java.lang.RuntimeException: Fail to connect to camera service
at android.hardware.Camera.open(Camera.java:499)
at com.google.zxing.client.android.camera.open.OpenCameraInterface.open(OpenCameraInterface.java:83)
at com.journeyapps.barcodescanner.camera.CameraManager.open(CameraManager.java:121)
at com.journeyapps.barcodescanner.camera.CameraInstance$3.run(CameraInstance.java:158)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:168)
at android.os.HandlerThread.run(HandlerThread.java:61)


解決方法只要加入以下程式碼即可

@Override
protected void onStart() {
    super.onStart();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        int hasCameraPermission = checkSelfPermission(Manifest.permission.CAMERA);
        List<String> permissions = new ArrayList<String>();

        if (hasCameraPermission != PackageManager.PERMISSION_GRANTED) {
            permissions.add(Manifest.permission.CAMERA);
        } 
        if (!permissions.isEmpty()) {
            requestPermissions(permissions.toArray(new String[permissions.size()]), 111);
        }
    }
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

    switch (requestCode) {
        case 111: {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                  
                } else if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                    
                }
            }
        }
        break;
        default: {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}
posted by admin in 程式&軟體 and have No Comments

Place your comment

Please fill your data and comment below.
Name
Email
Website
Your comment