当用户按下后退按钮或做出新意图时停止位置侦听器 activity

Stop a location listener activity when the user presses the back button, or when a new intent is made

只要用户的位置发生变化,此应用就会发出蜂鸣声。问题是,即使在用户离开应用程序并且应用程序处于后台后,该应用程序仍会继续监视用户的位置。

应用程序进入后台后,如何停止位置侦听器?

我想我必须向 OnPause() 添加一些东西,但我无法让它工作。

package com.example.locationbeeper;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;



public class MainActivity extends FragmentActivity implements LocationListener {

    LocationManager locationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // set up location manager
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String bestProvider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(bestProvider);
        if (location != null) {
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(bestProvider, 200, 5, this);  // time in miliseconds, distance in meters (Distance drains battry life) originally set to 20000 and 0
    }

    @Override
    public void onLocationChanged(Location location) {
        // beep when location changed
        final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
        tg.startTone(ToneGenerator.TONE_PROP_BEEP);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {

    }

    @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
    }

    @Override
    public void onPause(){
        super.onPause();
        
        locationManager = null;
    }


}

当 Activity 停止时,使用 LocationManager.removeUpdates 停止接收来自 LocationManager 的更新:

@Override
public void onStop(){
    super.onStop();
    if(locationManager !=null)
      locationManager.removeUpdates(this);
}

根据您的要求,您可以在 activity.

onPause()onStop() 回调方法中添加以下行
if(locationManager !=null)
      locationManager.removeUpdates(this);