Runtime Permissions:
To provide extra security of user’s personal data, Android 6.0 came up with Runtime permissions, which are supposed to be requested on demand while the application is running.
Steps:
1) Check whether the application is running in a device, whose version is greater than or equals Android 6.0-Marshmallow. To check that, we use Build class.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Version is greater than or equals 6.0
}else{
// Version is not greater than or equals 6.0
}
2) If the 1st step returns true, check the required permission enabled or not. If not enabled, request for the permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
String[] permissions = {Manifest.permission.ACCESS_COARSE_LOCATION};
ActivityCompat.requestPermissions(this, permissions, 2222);
}
}
3) Once the user allows or denies permission, we will have a method in Activity called with the results.
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
int result = grantResults[0];
if (result == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, “Location Enabled”, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, “Location Disabled”, Toast.LENGTH_SHORT).show();
}
}
In the above method, int[] grantResults parameter contains the results of permissions. It’s size is equals to the size of permissions we passed while requesting permissions. So, we iterate through that int array and check the permissions are enabled or not.
Create an Android application to work with Android Runtime permissions.