Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 761
Emmanuel Devaux Avatar asked Aug 26 '11 10:08

Emmanuel Devaux


People also ask

How check permission is granted or not Android?

To check if the user has already granted your app a particular permission, pass that permission into the ContextCompat. checkSelfPermission() method. This method returns either PERMISSION_GRANTED or PERMISSION_DENIED , depending on whether your app has the permission.

How do I request runtime permission?

Requesting Android Runtime Permissions For this the following method needs to be called on every permission. checkSelfPermission(String perm); It returns an integer value of PERMISSION_GRANTED or PERMISSION_DENIED.

What are runtime permissions?

(Android 5.1 and lower) Users grant dangerous permissions to an app when they install or update the app. Device manufacturers and carriers can preinstall apps with pregranted permissions without notifying the user.


2 Answers

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);             } 
like image 99
inazaruk Avatar answered Oct 16 '22 15:10

inazaruk


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 } 
like image 32
user123321 Avatar answered Oct 16 '22 15:10

user123321