我尝试在实现 LocationListener 的 FragmentActivity(为了用户 SupportMapFragment)中使用 LocationListener 获取用户的当前位置。
这是我的代码:
private void setLocationManager() {
if (lm == null)
lm = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
// exceptions will be thrown if provider is not permitted.
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (gps_enabled) {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
Toast.makeText(HomeActivity.this, "Refresh GPS", Toast.LENGTH_SHORT)
.show();
} else {
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
this);
Toast.makeText(HomeActivity.this, "Refresh NET", Toast.LENGTH_SHORT)
.show();
}
}
@Override
public void onLocationChanged(Location location) {
MyCurrentLocation = location;
Toast.makeText(
HomeActivity.this,
"Refresh == my lat : " + MyCurrentLocation.getLatitude()
+ " my long : " + MyCurrentLocation.getLongitude(),
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(HomeActivity.this, provider, Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(HomeActivity.this, provider, Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
我遇到的问题是:
- 被覆盖的方法:onLocationChanged 永远不会使用网络提供程序调用
- 被覆盖的方法:onProviderDisabled 永远不会每次都被调用。
而且我从不使用:lm.removeUpdate 方法