App crashes due to java.lang.SecurityException

前端 未结 5 924
甜味超标
甜味超标 2021-01-17 01:16

I am working on the project of capturing photos or picking images from gallery and show it in the recycler view, the app is working good in Android-lollipop but crashes in m

5条回答
  •  礼貌的吻别
    2021-01-17 01:58

    You must put Camera permission in code since android 6 + version checks for runtime permission.

    public void getCameraPermission(){
        if (!checkPermission()) {
            requestPermission();
        }
    }
    
    private boolean checkPermission(){
        int result = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
    
        if (result == PackageManager.PERMISSION_GRANTED){
            return true;
        } else {
            return false;
        }
    }
    
    private void requestPermission(){
        if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.CAMERA)){
    
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST_CODE);
        } else {
    
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST_CODE);
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                  Toast.makeText(MainActivity.this,"Permission granted",Toast.LENGTH_SHORT).show();
                    //store permission in shared pref
    
                }
    
                else {
                    Toast.makeText(MainActivity.this,"Permission denied",Toast.LENGTH_SHORT).show();
                    //store permission in shared pref
                }
                break;
        }
    }
    

提交回复
热议问题