这是我的Manifests
摘要:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
这是我的fragment's
摘要:
@Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
setInfoWindowAdapter();
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
this.googleMap.setMyLocationEnabled(true);
} else {
Toast.makeText(getActivity(), getString(R.string.no_permissions), Toast.LENGTH_LONG).show();
}
}
当我在一个Android 4.3中启动时,地图工作正常。但是,如果我从Android 6.0开始,我会收到消息(Toast)`无权限
答案 0 :(得分:1)
如果您在Android 6+上测试您的应用,那么您的代码工作正常。您需要在Android 6+上获得用户的运行时权限。以下是如何做到这一点:
int permissionCheck = ContextCompat.checkSelfPermission(MapActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MapActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
//permission is already granted
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//granted
} else {
//not granted
}
} else {
//not granted
}
}
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
答案 1 :(得分:0)
首先: 尝试使用它来请求权限:
boolean permissionGranted = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
if(permissionGranted) {
// {Some Code}
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 200);
}
第二: OnRequestPermissionsResultCallback的实现
...implements ActivityCompat.OnRequestPermissionsResultCallback {
第三: 覆盖onRequestPermissionsResult
方法
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 200: {
if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// {Some Code}
}
}
}
}