Android runtime permissions- how to implement

前端 未结 4 449
醉酒成梦
醉酒成梦 2020-11-30 11:25

Android Developer Documentation gives this example of requesting permissions at runtime:

// Here, thisActivity is the current activity
if (ContextCompat.chec         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-30 11:34

    Look just a little further down in the documentation under "Handle the permissions request response" and you will see its purpose.

    A callback method called onRequestPermissionsResult gets sent back the same code as a parameter so you know which permission was being requested/granted:

    @Override
    public void onRequestPermissionsResult(int requestCode,
            String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
    
                } else {
    
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
            }
    
            // other 'case' lines to check for other
            // permissions this app might request
        }
    }
    

    Since the constant is used by you only you can give it whatever value you like as a public static final int. Each permission being requested needs its own constant.

提交回复
热议问题