When to request permission at runtime for Android Marshmallow 6.0?

后端 未结 11 1013
故里飘歌
故里飘歌 2020-12-06 05:54

I am testing my app on Marshmallow 6.0 and it\'s getting force closed for the android.permission.READ_EXTERNAL_STORAGE, even if it is defined in th

11条回答
  •  日久生厌
    2020-12-06 06:12

    Do like this

    private static final int  REQUEST_ACCESS_FINE_LOCATION = 111;
    

    In your onCreate

    boolean hasPermissionLocation = (ContextCompat.checkSelfPermission(getApplicationContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED);
        if (!hasPermissionLocation) {
            ActivityCompat.requestPermissions(ThisActivity.this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    REQUEST_ACCESS_FINE_LOCATION);
        }
    

    then check result

       @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode)
        {
    
            case REQUEST_ACCESS_FINE_LOCATION: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {
                    Toast.makeText(ThisActivity.this, "Permission granted.", Toast.LENGTH_SHORT).show();
    
                    //reload my activity with permission granted
                    finish();
                    startActivity(getIntent());
    
                } else
                {
                    Toast.makeText(ThisActivity.this, "The app was not allowed to get your location. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
                }
            }
    
        }
    
    }
    

提交回复
热议问题