【发布时间】:2020-08-07 13:15:37
【问题描述】:
因此基于此提出了许多类似的问题,我也得到了一个可行的解决方案。但是,这似乎只适用于我的物理 Android 设备。如果我将它与模拟器一起使用,该方法会返回一个空值,我不知道为什么。许多消息来源提到我目前使用的代码有更好的替代方案,但他们没有提到具体是什么/如何。这是我用来获取设备当前位置的代码:
@SuppressWarnings("MissingPermission")
private LatLng getCurrentLocation() {
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
String locationProvider = LocationManager.NETWORK_PROVIDER;
assert locationManager != null;
android.location.Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
return new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
}
我也不喜欢必须隐藏警告的事实。我查看的来源包括:
https://developer.android.com/training/location/retrieve-current.html#java
What is the simplest and most robust way to get the user's current location on Android?
第一个不起作用,我得到一个空值。对于我正在寻找的简单结果,第二个看起来过于复杂。
【问题讨论】: