Destil 的上述回答正确处理了至少一个提供者为getLastKnownLocation() 返回有效位置的情况。
但是,我也看到 Glass 为所有提供商(特别是 XE16)返回 null 为 getLastKnownLocation()。
在这种情况下,您唯一的选择是注册 LocationListener 并等待新的位置更新。
例如,在创建新 Activity 时获取位置的上下文中,它将如下所示:
public class MyActivity extends Activity implements LocationListener {
...
LocationManager mLocationManager;
Location mLastKnownLocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
// Activity setup
...
// Use Destil's answer to get last known location, using all providers
mLastKnownLocation = getLastLocation(this);
if (mLastKnownLocation != null) {
// Do something with location
doSomethingWithLocation(mLastKnownLocation);
} else {
// All providers returned null - start a LocationListener to force a refresh of location
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
for (Iterator<String> i = providers.iterator(); i.hasNext(); ) {
mLocationManager.requestLocationUpdates(i.next(), 0, 0, this);
}
}
...
}
...
}
然后您需要处理 LocationListener 回调:
@Override
public void onLocationChanged(Location location) {
if (mLastKnownLocation == null) {
// At least one location should be available now
// Use Destil's answer to get last known location again, using all providers
mLastKnownLocation = getLastLocation(this);
if (mLastKnownLocation == null) {
// This shouldn't happen if LocationManager is saving locations correctly, but if it does, use the location that was just passed in
mLastKnownLocation = location;
}
// Stop listening for updates
mLocationManager.removeUpdates(this);
// Do something with location
doSomethingWithLocation(mLastKnownLocation);
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onProviderDisabled(String provider) {}
更改为异步模型以避免在等待更新时阻塞 UI 线程可能有点棘手,并且可能需要移动一些应用程序逻辑。