在MyApplication
启动应用程序时,如果用户未登录,我将使用标记FLAG_ACTIVITY_NEW_TASK
开始登录活动。在onCreate()
内的此登录活动中,我正在请求位置权限。权限对话框显示但在用户有机会执行任何操作之前会自动被解除。为什么会这样?
我在onCreate方法的第一行请求这样的许可:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && (ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mActivity.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_LOCATION_ACCESS_CODE);
}
答案 0 :(得分:0)
确保已包含
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
你的清单中的
在你的onCreate()中检查是否允许权限
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&!isPermissionAllowed()){
ActivityCompat.requestPermissions(Home.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}else{
//continue execution
}
}
private boolean isPermissionAllowed(){
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
)!=PackageManager.PERMISSION_GRANTED){
return false;
}
return true;
}