如何在MapActivity启动时通过GPS或WiFi获取当前位置

时间:2012-08-10 13:39:44

标签: android geolocation gps location

我必须在MapActivity启动时加载当前设备位置(它从另一个Activity启动的Intent开始)。
问题是环顾网页和Android开发者部分我发现我必须使用LocationListener方法onLocationChange(位置),但我必须在MapActivity启动时获取用户位置,而不是在用户更改其位置时。我尝试了各种方法,但我没有找到解决方案。

public class MappaActivity extends MapActivity {

MapView miaMapView;
MapController mc;
LocationManager lm;
GeoPoint actualP;
LocationListener locationListener;

@Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_mappa_activity);

    miaMapView=(MapView)findViewById(R.id.miaMapView);
    mc=miaMapView.getController();
    miaMapView.setBuiltInZoomControls(true);
    miaMapView.setSatellite(true);
    miaMapView.invalidate();

    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    locationListener=new MyLocationListener();

    lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, locationListener);


//  This is MyLocationListener inner class:



private class MyLocationListener implements LocationListener{

    @Override
    public void onLocationChanged(Location location) {
        if(location!=null){

            actualP = new
                    GeoPoint(
                    (int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6));

            mc.animateTo(actualP);
            mc.setZoom(10);
        }

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

}

}

actualP保持为null,在用户位置更改之前不会触发onLocationChanged方法。

我也尝试过使用locationManager.getLastKnowLocation(location.GPS_PROVIDER),但它返回null。

我希望能找到一些帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

您的GPS_PROVIDER可能无法获取位置

如果您在GPS_PROVIDER无法为您提供位置时也使用NETWORK_PROVIDER和PASSIVE_PROVIDER获取位置,那会更好

也使用lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListener);

和lm.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER,0,0,locationListener);也许它们不像GPS_PROVIDER那么准确。