代码之家  ›  专栏  ›  技术社区  ›  Tima

如何停止位置管理器?

  •  31
  • Tima  · 技术社区  · 14 年前

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

    我在一个活动中调用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();
     }
    }
    

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

    5 回复  |  直到 6 年前
        1
  •  12
  •   Darkhogg    12 年前

    有没有可能你的活动没有被破坏?i、 e:你按了home键。将gps开始/停止移动到 onStart onPause .

        2
  •  27
  •   bpz    11 年前

    你应该调用方法 removeUpdates 方法内部 onPause :

    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
        Log.i(TAG, "onPause, done");
    }
    
        3
  •  8
  •   CommonsWare    14 年前

    一旦加载,仿真器就永远不会去掉GPS图标。因此,在模拟器上,不能使用GPS图标作为GPS是否仍在运行的测试。不过,在设备上,图标应该会消失。

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

    我当然会的。我不知道是否 removeUpdates() 将同时删除这两个请求,或者即使这两个请求都已注册到单个侦听器。

        4
  •  3
  •   Sabari Esh    8 年前

    我使用: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);
    }
    
        5
  •  2
  •   Alex    14 年前

    我知道这篇文章发表已经有一段时间了,但也许它能帮助其他人。我使用:removeUpdates(这个),因为我的监听器是我实现de location manager的活动,所以需要指示监听器。

    推荐文章