1

我是 Android 开发的新手。我正在尝试管理活动之间的 gps 位置。特别是,我创建了一个线程,从主要活动开始,在间隔几个间隔后更新 gps 位置并将新位置保存到共享 Bean 中。现在,当我将 Bean 作为附加项传递给下一个活动时,我可以获得 bean 的最后一个值,但是线程不会更新新活动上的 bean。我没有创建新的 Bean,因此我认为 bean 的更新会在新活动中看到。有我用来在新活动中检索额外内容的代码:

    ShareBean pos;
    Intent intent = getIntent();
    Bundle extras = getIntent().getExtras();
    if (extras != null)
    {
        pos = (ShareBean)intent.getSerializableExtra("Location");
    }

任何帮助表示赞赏。提前感谢。西蒙娜

4

1 回答 1

0

您可能应该使用该LocationManager对象来获取和访问位置更新。您可以查询它以获取最后一个已知位置以进行快速更新。

关键是,我要求位置经理开始收听,然后我可以随时要求快速更新。我将更新的位置信息存储在我的ApplicationContext对象(我appModel在本地调用)中,该信息在对象的整个生命周期中都是持久的。

我使用LocationManager这样的:

locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
startListening();

开始收听看起来像这样:

public void startListening() {

    if (gpsLocationListener == null) {
        // make new listeners
        gpsLocationListener = new CustomLocationListener(LocationManager.GPS_PROVIDER);

        // request very rapid updates initially. after first update, we'll put them back down to a much lower frequency
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 200, gpsLocationListener);
    }

    //get a quick update
    Location networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

    //this is the applicationContext object which persists for the life of the applcation
    if (networkLocation != null) {
        appModel.setLocation(networkLocation);
    }
}

您的位置侦听器可能如下所示:

private class CustomLocationListener implements LocationListener {

    private String provider = "";
    private boolean locationIsEnabled = true;
    private boolean locationStatusKnown = true;

    public CustomLocationListener(String provider) {
        this.provider = provider;
    }

    @Override
    public void onLocationChanged(Location location) {
        // Called when a new location is found by the network location provider.
        handleLocationChanged(location);
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    public void onProviderEnabled(String provider) {
        startListening();
    }

    public void onProviderDisabled(String provider) {
    }
}

private void handleLocationChanged(Location location) {

    if (location == null) {
        return;
    }

    //get this algorithm from: http://developer.android.com/guide/topics/location/obtaining-user-location.html
    if (isBetterLocation(location, appModel.getLocation())) {
        appModel.setLocation(location);
        stopListening();
    }
}

祝你好运!

于 2011-07-29T19:05:28.853 回答