Record a big pit of Android 6.0 permission problem

When using the Camera class, I wrote it in accordance with the official API, and it flashed back and reported a null pointer at the beginning! Tracing back to the source, the camera is not instantiated, but I have already Camera.open()! ! Ever since, I checked the code again and found no problems! And the permissions are also allocated! Nima, is the official document wrong? At this time, I thought of the omnipotent Baidu, and found that  after Android 6.0, there is a kind of runtime permission, and it happens that Camera is also included. I probably looked at the meaning, that is, the permissions allocated in mainfest will not take effect when the app is installed, but when it is changed to run, a dialog box will pop up for the user to choose whether to enable this permission! I instantly remembered that the Android version of my phone was upgraded to above 6.0 a few days ago! Suddenly~ Ten thousand horses in my heart rushed past Nima! The reason for the crash: When the program directly requested camera.open() during operation, it did not actually obtain the permission to operate the Camera.

Therefore, when starting the Camera, add some judgment:

public void open(View view){
        //先判断用户之前是否已经授予过该权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            startActivity(new Intent(this,CaptureActivity.class));
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 用户授予权限
                    startActivity(new Intent(this,CaptureActivity.class));
                } else {
                    // 用户拒绝权限
                }
                return;
            }
        }
    }


When running, it will first pop up whether to open the permission related to running, click OK to open, and then you can play happily~~

The dangerous permissions prescribed by Android 6.0 are as follows:

Permission Group Permissions
CALENDAR
CAMERA
CONTACTS
LOCATION
MICROPHONE
PHONE
SENSORS
SMS
STORAGE

Guess you like

Origin blog.csdn.net/lc547913923/article/details/53116526