-1

When the permission Dialog pops up, it asks if I want to allow or deny a certain permission. Thing is, when I allow or deny, the action doesn't execute. How do I know if he allowed so I can execute an action upon accepting?

I tried:

int hasWriteExternalStoragePermission = ctx.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
    if (hasWriteExternalStoragePermission == PackageManager.PERMISSION_GRANTED) {
        // my code
    }

But it doesn't execute as it's "too late"

Montassir Ld
  • 531
  • 4
  • 12
  • Check this http://stackoverflow.com/a/31925748/2435238 – Sujay Jan 23 '17 at 07:09
  • You should follow the guide about [Runtime Permission](https://developer.android.com/training/permissions/requesting.html). This is usually a good start on Android basics – AxelH Jan 23 '17 at 07:13

1 Answers1

0

Try this way :

public  boolean isStoragePermissionGranted() 
{
    if (Build.VERSION.SDK_INT >= 23) 
    {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) 
        {
            Log.v(TAG,"Permission is granted");
            return true;
        } 
        else 
        {

            Log.v(TAG,"Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    }
    else 
    { 
        //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG,"Permission is granted <23");
        return true;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) 
{
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults[0]== PackageManager.PERMISSION_GRANTED)
    {
        Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
        //resume tasks needing this permission
    }

   else
   {
       Log.v(TAG,"Permission denied");
   }
}

This way, If the permission is granted it would come here:

  • Log.v(TAG,"Permission is granted");

If permission is not already granted , it would come here:

  • Log.v(TAG,"Permission is revoked"); and try get the permission.

And if user grants the permission in runtime :

  • Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);

if the user denies it :

  • Log.v(TAG,"Permission denied");

In case the version is below Marshamallow, ie below API 23, then it would come here:

  • Log.v(TAG,"Permission is granted <23");
OBX
  • 6,044
  • 7
  • 33
  • 77