问题
I am working on Android Marshmallow runtime permissions. I asked user for location permission, suppose he has allowed to get the location and i have started getting location but now user has denied the permission from settings of application. Now application has crashed. How can i handle it? Please help.
回答1:
This is worked for me !!! In Your Splash Activity of your application do the following,
Note: If user disables the permission after some time, these piece of code will not allow to get into the application without any crashes, it asks a dialog to allow that needed permission.
1) Declare an int variable for request code,
private static final int REQUEST_CODE_PERMISSION = 2;
2) Declare a string with the permissions name that you need,
String mPermission = Manifest.permission.ACCESS_FINE_LOCATION,
3) Next Check the condition for runtime permission on your onCreate method,
try {
if (ActivityCompat.checkSelfPermission(this, mPermission)
!= MockPackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
mPermission, REQUEST_CODE_PERMISSION);
// If any permission above not allowed by user, this condition will execute every time, else your else part will work
}
} catch (Exception e) {
e.printStackTrace();
}
4) Now Declare onRequestPermissionsResult method to check the request code,
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.e("Req Code", "" + requestCode);
if (requestCode == REQUEST_CODE_PERMISSION) {
if (grantResults.length == 1 &&
grantResults[0] == MockPackageManager.PERMISSION_GRANTED ) {
// Success Stuff here
}
else{
// Failure Stuff
}
}
}
回答2:
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
//here req again for Permission
}
}
来源:https://stackoverflow.com/questions/34871432/android-marshmallow-location-permission-handling