[英]Android Marshmallow Location Permission handling
I am working on Android Marshmallow runtime permissions. 我正在使用Android Marshmallow运行时权限。 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.
请帮忙。
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, 1)为请求代码声明一个int变量,
private static final int REQUEST_CODE_PERMISSION = 2;
2) Declare a string with the permissions name that you need, 2)声明一个带有所需权限名称的字符串,
String mPermission = Manifest.permission.ACCESS_FINE_LOCATION,
3) Next Check the condition for runtime permission on your onCreate method, 3)接下来,检查onCreate方法的运行时权限条件,
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, 4)现在声明onRequestPermissionsResult方法以检查请求代码,
@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
}
}
}
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
//here req again for Permission
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.