Android - Requesting Runtime Permissions

后端 未结 1 710
故里飘歌
故里飘歌 2021-01-27 04:02

I am trying to understand how to request Runtime Permissions in android for \"Dangerous permissions\" like Location.

What i understand is that the code should go like th

相关标签:
1条回答
  • 2021-01-27 04:47

    Try this, it worked for me

    private void checkPermission() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
    
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},
                    MY_PERMISSIONS_REQUEST_FINE_LOCATION);
    
        } else {
            getLocation();
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_FINE_LOCATION: {
                // 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.
                 getLocation();
                } else {
                    // permission denied, boo! Disable the
                }
                return;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题