New runtime permissions in Android-M asking for minimum 23 API level, but I still need minimum 16 API level in my project.
So, how to make this code more forward-compatible?
Regards
New runtime permissions in Android-M asking for minimum 23 API level, but I still need minimum 16 API level in my project.
So, how to make this code more forward-compatible?
Regards
Use ContextCompat.checkSelfPermission()
, ActivityCompat.requestPermissions()
, and ActivityCompat.shouldShowPermissionRequestRationale()
, from the support-v4
library (v23 or higher). These are backwards-compatible; if you are running on an older version of Android, they will "do the right thing" (e.g., return PackageManager.PERMISSION_GRANTED
for ContextCompat.checkSelfPermission()
).
Just Check your android version before get check permission:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// public void requestPermissions(@NonNull String[] permissions, int requestCode)
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
return;
}
}else{
//Do Your Stuff
}
In case you dont want to use AppCompatActivity the way is described here https://codemammoth.blogspot.gr/2016/06/how-to-invoke-checkselfpermission.html
You have to invoke the methods :)
You can check the build version if(Build.Version.SDK_INT >= Build.VERSION_CODES.MARSHMALLOW)
. And then handle marshmallow permissions in there, and handle the other versions otherwise.
checkSelfPermission is available above sdk 23.
we can check the permission is available or not using package manager
public static Boolean checkpermissions(Activity activity) {
PackageManager mPackageManager = activity.getPackageManager();
int hasPermStorage = mPackageManager.checkPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, activity.getPackageName());
if (hasPermStorage != PackageManager.PERMISSION_GRANTED) {
// do stuff
//Toast.makeText(getApplicationContext(), "No permission", Toast.LENGTH_LONG).show();
return false;
} else if (hasPermStorage == PackageManager.PERMISSION_GRANTED) {
// do stuff
//Toast.makeText(getApplicationContext(), "Has permission", Toast.LENGTH_LONG).show();
return true;
}else
return false;
}