How permission can be checked at runtime without throwing SecurityException?

I design a function that may get/set a resource from SD and if not found from sd then take it from Asset and if possible write the asset back to SD
This function may check by method invocation if SD is mounted and accessible...

boolean bSDisAvalaible = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);

My designed function may be used from one app(project) to another (with or without android.permission.WRITE_EXTERNAL_STORAGE)

Then I would like to check if the current application has this particular permission without playing with SecurityException.

Does it exist a "nice" way to consult current defined permissions at runtime ?


Solution 1:

You can use Context.checkCallingorSelfPermission() function for this. Here is an example:

private boolean checkWriteExternalPermission()
{
    String permission = android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
    int res = getContext().checkCallingOrSelfPermission(permission);
    return (res == PackageManager.PERMISSION_GRANTED);            
}

Solution 2:

This is another solution as well

PackageManager pm = context.getPackageManager();
int hasPerm = pm.checkPermission(
    android.Manifest.permission.WRITE_EXTERNAL_STORAGE, 
    context.getPackageName());
if (hasPerm != PackageManager.PERMISSION_GRANTED) {
   // do stuff
}

Solution 3:

You can also use this:

private boolean doesUserHavePermission()
{
    int result = context.checkCallingOrSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
    return result == PackageManager.PERMISSION_GRANTED;
}