【问题标题】:How to stop automatic updates of Location如何停止位置的自动更新
【发布时间】:2018-05-13 07:15:49
【问题描述】:

我正在创建一个应用程序,每次单击按钮时都会更新位置(纬度,经度)。 我在调用此方法的按钮上设置了一个 OnClickListener -

 void getLocation() {
    try{
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //Default minTime = 5000, minDistance = 5
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, this);
    }
    catch (SecurityException e) {
        e.printStackTrace();
    }
}

但问题是该位置会在很短的时间内不断自我更新。我希望位置保持不变,并且仅在按下按钮时自行更新。我必须进行哪些修改才能做到这一点?

这里是 onLocationChanged() 方法供参考 -

@Override
public void onLocationChanged(Location location) {

    locationText.setText("Current Location: "+ location.getLatitude() + " , " + location.getLongitude());
}

而且,有时它会在一秒钟内显示位置,而有时需要 10 秒。有什么原因/解决方案吗?

【问题讨论】:

    标签: java android android-location


    【解决方案1】:

    实际上,当您不想自动更新位置时,首先不需要requestLocationUpdates()

    所以不是

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, this);
    

    随便用

    locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, this, null);
    

    那么你每次点击按钮只会得到一个回调。

    关于收到回调的时间段:Android 力求尽可能减少电池消耗。这包括每次单个应用请求位置时都不会检测到该位置,而是将请求捆绑在一起,以便将一个接收到的位置传递给请求该位置的多个应用或服务。

    【讨论】:

      【解决方案2】:

      如果您只想在单击按钮时更新,您可以简单地将值存储在回调中,并且在您单击按钮之前不更新 UI

      private Location mLocation;
      @Override
      public void onLocationChanged(Location location) {
           mLocation = location;
      }
      

      将此移到按钮点击方法中

      locationText.setText("Current Location: "+ mLocation.getLatitude() + " , " + mLocation.getLongitude());
      

      GPS 的准确性可能与它的更新频率有关

      【讨论】:

        【解决方案3】:

        你可以使用

        locationManager.removeUpdates(this);
        

        更多信息here

        【讨论】:

          猜你喜欢
          • 2023-03-10
          • 1970-01-01
          • 2017-05-30
          • 1970-01-01
          • 2019-02-06
          • 1970-01-01
          • 1970-01-01
          • 2011-10-02
          • 1970-01-01
          相关资源
          最近更新 更多