I am developing my project in SDK version 23 where app permissions were newly introduced. In some guidelines they were using below code to read phone state permission is granted or not
if (ContextCompat.checkSelfPermission(serviceContext, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
//Read Phone state
}else{
}
But i am directly accessing checkSelfPermission
like below
if(serviceContext.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
//Read Phone state
}else{
}
It's working fine. My question is what's the difference between above these codes?.which is the correct way to check for permission granted or not?
My question is what's the difference between above these codes?
None, on API 23(+) devices.
Devices running an older version of Android, however, will generate an error through when you try to call context.checkSelfPermission()
directly. This method wasn't available until API 23.
ContextCompat
provides a backwards compatible way to run checkSelfPermission()
on older APIs too. If you look at the implementation, you'll see it accomplishes this by simply delegating the call to checkPermission()
with the app's own process parameters. checkPermission()
has been available since very first API release and will thus work across the board.
public static int checkSelfPermission(@NonNull Context context, @NonNull String permission) {
if (permission == null) {
throw new IllegalArgumentException("permission is null");
}
return context.checkPermission(permission, android.os.Process.myPid(), Process.myUid());
}
which is the correct way to check for permission granted or not?
So, to answer this question: if you're only supporting devices running Android 'Marshmallow' 6.0 and newer, then you can use either approach. However, since it's more likely you also want to support some older versions of Android, use ContextCompat
.