我知道这个问题已经被讨论过很多次了,但是没有任何东西可以帮助我解决 getLastKnownLocation 返回 null 的问题。
我的活动实现 LocationListener:
public class MainActivity extends Activity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
我的 onCreate 方法中有这个:
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
然后我尝试像这样获取用户位置(也在 onCreate 中):
// Getting the Co-ordinates of the users current location
Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null){
longitude = location.getLongitude();
latitude = location.getLatitude();
}
我当时尝试过:
@Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
我错过了什么吗?
编辑:仍然不起作用,但我尝试过的代码:
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
while (location == null) {
if (counter > MAX_TIME) {
}
else {
try {
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
counter += 1000;
}
}
}