【发布时间】:2013-01-06 11:05:49
【问题描述】:
获取当前位置的代码如下:
final LocationManager manager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener listener=new LocationListener() {
@Override
public void onLocationChanged(Location location) {
manager.removeUpdates(this);
Toast.makeText(MainActivity.this, "2", Toast.LENGTH_LONG).show();
if (location!=null) {
doSomeAction();
}
else {
Toast.makeText(MainActivity.this, LOCATION_IS_NULL_MESSAGE, Toast.LENGTH_LONG).show();
}
}
@Override
public void onProviderDisabled(String provider) {
manager.removeUpdates(this);
String newProvider=provider.equals(LocationManager.GPS_PROVIDER) ? LocationManager.NETWORK_PROVIDER : null;
if (newProvider==null) {
Toast.makeText(MainActivity.this, LOCATION_PROVIDERS_ARE_DISABLED_MESSAGE, Toast.LENGTH_LONG).show();
}
else {
manager.requestLocationUpdates(newProvider, 0, 0, this);
}
}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {}
};
String provider=manager.isProviderEnabled(LocationManager.GPS_PROVIDER) ? LocationManager.GPS_PROVIDER :
LocationManager.NETWORK_PROVIDER;
Location location=manager.getLastKnownLocation(provider);
if (location!=null) {
doSomeAction();
}
else {
Toast.makeText(this, "1", Toast.LENGTH_LONG).show();
manager.requestLocationUpdates(provider, 0, 0, listener);
}
我每次都看到 toast "1",但我从未见过 "2" toast,因此我的位置不会更新。请告诉我,我需要获取当前位置 - 如何解决我的问题?我使用网络位置提供程序。
【问题讨论】:
-
你真的改变了你的位置吗?
-
我在5米内改变了我的位置,但我相信如果没有最后一个已知位置,我会立即得到我的当前位置,因为我只需要得到当前位置。
-
为了确保它工作,尝试模拟相当大的location change in emulator。
-
但是我的代码是对的吗?
-
尝试删除
manager.removeUpdates(this);在onLocationChanged
标签: android android-location locationlistener