If your application is targeting an API level before 23 (Android M) then both:ContextCompat#checkSelfPermission and Context#checkSelfPermission doesn't work and always returns 0 (PERMISSION_GRANTED). Even if you run the application on Android 6.0 (API 23).html
It's not fully true that if you targeting an API level before 23 then you don't have to take care of permissions. If you targeting an API level before 23 then:java
Android < 6.0: Everything will be ok.android
Android 6.0: Application's run-time permissions will be granted by default (compatibility mode applies), but the user can change run-time permissions in Android Settings, then you may have a problem.app
As I said in the 1st point, if you targeting an API level before 23 on Android 6.0 then ContextCompat#checkSelfPermission and Context#checkSelfPermission doesn't work. Fortunately you can use PermissionChecker#checkSelfPermission to check run-time permissions.ui
Example code:code
public boolean selfPermissionGranted(String permission) { // For Android < Android M, self permissions are always granted. boolean result = true; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (targetSdkVersion >= Build.VERSION_CODES.M) { // targetSdkVersion >= Android M, we can // use Context#checkSelfPermission result = context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED; } else { // targetSdkVersion < Android M, we have to use PermissionChecker result = PermissionChecker.checkSelfPermission(context, permission) == PermissionChecker.PERMISSION_GRANTED; } } return result; }
In order to obtain target Sdk Version you can use:htm
try { final PackageInfo info = context.getPackageManager().getPackageInfo( context.getPackageName(), 0); targetSdkVersion = info.applicationInfo.targetSdkVersion; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); }
It works on Nexus 5 with Android M.get