开发者

How do I stop GPS/location tracking when my Activity finishes?

I have a very simple app for Android that displays a Google Maps view and uses the GPS to track 开发者_高级运维the position (essentially like so):

public void onCreate(Bundle savedInstanceState) {
    // ...
    mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    // ...
}

public void onResume() {
    super.onResume();
    mLocationManager.requestLocationUpdates(mProvider, 20000, 1, this);
}

public void onPause() {
    super.onPause();
    mLocationManager.removeUpdates(this);
}

public void onLocationChanged(Location location) {
    mPosition = getGeoPointForLocation(location);
    mMapController.setCenter(mPosition);
}

And when I use the following command to exit the application (e.g. through a menu), the GPS keeps on tracking - it seems that the Activity is still running:

// ...
case R.id.menu_exit:
    finish();
// ...

How do I stop the GPS tracking if it does not work by removing the location manager in onPause() and calling finish()? As far as I have read tutorials or other questions, this should be the solution..


Are you using MyLocationOverlay? This gives you the pulsating blue dot that represents your current position. I didn't see MyLocationOverlay in your sample code but I'm just double checking.

If you are using MyLocationOverlay...

I've tested the code below: with and without calling "disableMyLocation" when I exit a sample app after pressing an "exit" menu command. When I call "disableMyLocation", the GPS tracking turns off. When I don't call it, the GPS tracking stays on after I call "finish".

    public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.quit:

        myLocOverlay.disableMyLocation(); //turn off location
        mlocManager.removeUpdates(this); // no impact on GPS tracking
        finish(); //destroy Android app
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}


Are you sure you are not entering again in the Activity? Are you sure you are actually stopping the GPS? Try to make a timer that after 2 seconds calls mLocationManager.removeUpdates(this), just to make sure you can actually stop it. You can also check if your activity is paused.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜