【发布时间】:2017-01-10 21:47:46
【问题描述】:
我正在尝试实现 Marshmallow 的权限支持,但我在“onRequestPermissionsResult”中的代码从未被调用过。代码的“onCreate”和“onMapReady”部分工作正常。检查设备是否有权限并请求权限工作正常。
我正在使用运行 Android Marshmallow 6.0、API 23 的 Nexus 5X 模拟器。
我已经尝试过这里提到的 -> Android M Permissions: onRequestPermissionsResult() not being called
但我无法让它工作,无论我使用“ActivityCompat.requestPermissions”还是直接“requestPermissions”,它都不会被调用。
我还将我的 appcompat 和支持库更新到 v24.2.0
有什么想法吗?
这是我的活动:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
UiSettings mapSettings;
int MY_LOCATION_REQUEST_CODE;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Check location permission for sdk >= 23
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
// Request permission.
ActivityCompat.requestPermissions(MapsActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_LOCATION_REQUEST_CODE);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == MY_LOCATION_REQUEST_CODE) {
if (permissions.length == 1 &&
permissions[0] == android.Manifest.permission.ACCESS_FINE_LOCATION &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
// Permission was denied. Display an error message.
}
}
}
}
【问题讨论】:
-
您的设备/模拟器正在运行什么 API?
-
也许这是一个愚蠢的问题,但您实际上是在 API > 23 的设备/模拟器上运行应用程序吗?请求权限对话框是否显示?
-
我使用的是运行 Android Marshmallow 6.0, api 23 的 Nexus 5X 模拟器
-
你为什么不在 OnCreate 或 Better 是在调用 MapsActivity 之前做呢?因为 OnMapReady 是一个线程进程,所以它只有在准备好时才会触发。