如何停止位置经理?

Tim*_*ima 33 gps android locationmanager

不知道为什么,但有时候LOCManager在关闭应用程序后仍然可以工作.

我在一个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();
 }
}
Run Code Online (Sandbox Code Playgroud)

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

public void endGPS(){
 try {           
     lmanager.removeUpdates(this);
     lmanager=null;
 } catch(Exception e) {
  e.printStackTrace();
 }
}
Run Code Online (Sandbox Code Playgroud)

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

小智 27

你应该在方法中调用removeUpdates方法onPause:

@Override
protected void onPause() {
    super.onPause();
    locationManager.removeUpdates(this);
    Log.i(TAG, "onPause, done");
}
Run Code Online (Sandbox Code Playgroud)


Nat*_*ann 12

你的活动有可能不被破坏吗?即:你点击主页按钮.将你的gps开始/停止移动到onStartonPause.


Com*_*are 8

一旦加载,模拟器永远不会摆脱GPS图标.因此,在模拟器上,您无法使用GPS图标作为GPS是否仍在运行的测试.但是,在设备上,图标应该消失.

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

我肯定会.我不知道是否removeUpdates()会删除这两个请求,或者即使两个请求都注册了单个侦听器.


小智 5

我使用: locationManager.removeUpdates(locationListener); 它的工作

    @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);
}
Run Code Online (Sandbox Code Playgroud)