当您尝试检索最后一个已知位置时,即使在添加回调之后,也不会调用onConnected(),可能是由于以下几个原因:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
并且在运行时动态请求权限:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSION);
}
FusedLocationProviderClient
来请求位置更新并设置回调函数:FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
fusedLocationClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
// 处理获取到的位置信息
}
}
});
腾讯云相关产品推荐:
领取专属 10元无门槛券
手把手带您无忧上云