35

不知道为什么,但有时 LocationManager 在关闭应用程序后仍在工作。

我在一个 Activity 中调用 onCreate-Methode 中的 startGPS()(只有一个,让我称之为 StartActivity)。

protected void startGPS(){    
 try {           
     lmanager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
     lmanager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
     lmanager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
 } catch(Exception e) {
     e.printStackTrace();
 }
}

如果此活动将被销毁(因此,当应用程序关闭时),我调用 endGPS()

public void endGPS(){
 try {           
     lmanager.removeUpdates(this);
     lmanager=null;
 } catch(Exception e) {
  e.printStackTrace();
 }
}

一些想法,一些建议,我做错了什么?!

4

6 回答 6

33

You should call the method removeUpdates inside the method onPause:

@Override
protected void onPause() {
    super.onPause();
    locationManager.removeUpdates(this);
    Log.i(TAG, "onPause, done");
}
于 2014-07-17T09:54:20.743 回答
13

您的活动是否有可能没有被破坏?即:您按下主页按钮。将您的 GPS 开始/停止移动到onStartonPause

于 2010-11-16T18:19:36.190 回答
8

模拟器一旦加载就永远不会摆脱 GPS 图标。因此,在模拟器上,您不能使用 GPS 图标来测试 GPS 是否仍在运行。但是,在设备上,图标应该会消失。

我应该使用两个不同的听众吗?

I sure would. I do not know whether removeUpdates() will remove both, or even if both requests are registered with the single listener.

于 2010-11-16T22:25:51.687 回答
5

I use: locationManager.removeUpdates(locationListener); Its Working

    @Override
protected void onPause() {
    super.onPause();
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }


    locationManager.removeUpdates(locationListener);
}
于 2016-09-07T10:27:52.137 回答
2

I see it´s been a while since this post, but maybe it would help some body else. I use: removeUpdates(this), because my listener it´s the activity where I implement de location manager, you need to indicate your listener.

于 2011-08-17T17:58:26.593 回答
0

Quite an old queerie but this works for me.

       @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        mLocationManager.removeUpdates(locationListener);

        }
于 2020-05-22T23:20:37.563 回答