【发布时间】:2020-03-09 07:03:07
【问题描述】:
好吧,即使在这里阅读很多,我也无法弄清楚问题所在。看来我从来没有开启 gps 事件。
经过一些调试检查,标志 isGps 是正确的。但结果,用户警报效果很好,但不能更新位置。我只想在打开 gps 时添加一个标记,并且看起来这里有些东西没有正确同步。
即使定位精度很高。
我使用片段中的这段代码。
public class MapDialogFragment extends DialogFragment
implements OnMapReadyCallback, GoogleMap.OnMarkerDragListener {
.....
private BroadcastReceiver mGpsSwitchStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (LocationManager.PROVIDERS_CHANGED_ACTION.equals(intent.getAction())) {
boolean isGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(isGPS){
// never goes here WHEN GPS TURNED ON !!! WHY ?? MAKES ME CRAZY
// + how get current location here ? is updateMyLocation call ok ?
updateMyLocation();
}
else{
// user alert
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.message_location_error_gps_off), Toast.LENGTH_LONG).show();
}
}
}
};
@Override
public void onResume() {
super.onResume();
getContext().registerReceiver(mGpsSwitchStateReceiver, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));
}
@Override
public void onPause() {
super.onPause();
getContext().unregisterReceiver(mGpsSwitchStateReceiver);
}
private void updateMyLocation(){
Task locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(getActivity(), new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful() && task.getResult() != null) {
// Set the map's camera position to the current location of the device.
mLastKnownLocation = (Location) task.getResult();
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(mLastKnownLocation.getLatitude(),
mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
latitude = mLastKnownLocation.getLatitude();
longitude = mLastKnownLocation.getLongitude();
// add marker
buildMarkerFromLocation();
} else {
Log.d(TAG, "Current location is null. Using defaults.");
Log.e(TAG, "Exception: %s", task.getException());
}
}
});
}
...
}
所以这是我的逻辑:
- 检查 GPS 是否打开
- 如果是发送mFusedLocationProviderClient.getLastLocation()请求
- 获取结果,但在 GPS 刚打开时总是没有结果
所以基本上,如何提供一个没有硬代码的默认位置?
这里是关于 google api 页面的更多信息:
getLastLocation() 方法返回一个 Task,您可以使用该 Task 获取具有地理位置的纬度和经度坐标的 Location 对象。位置对象在以下情况下可能为空:
位置在设备设置中被关闭。即使先前检索到最后一个位置,结果也可能为空,因为禁用位置也会清除缓存。
设备从未记录其位置,可能是新设备或已恢复出厂设置的设备。
设备上的 Google Play 服务已重新启动,并且在服务重新启动后没有活动的 Fused Location Provider 客户端请求位置。为避免这种情况,您可以创建一个新客户端并自己请求位置更新。有关详细信息,请参阅接收位置更新。
希望我能在您的帮助下解决这个问题。应该是显而易见的,但我不知道出了什么问题......
【问题讨论】:
-
您确定广播接收者是否收到事件?
-
我每次都会收到事件(断开/连接),但不幸的是,问题似乎出在 updateMyLocation 中,因为当 GPS 打开时,标记并没有在地图上添加一个,如何解决这个问题?
标签: android broadcastreceiver android-gps location-provider