【问题标题】:Get Current Location on Geofence.GEOFENCE_TRANSITION_EXIT在 Geofence.GEOFENCE_TRANSITION_EXIT 上获取当前位置
【发布时间】:2017-03-02 07:41:21
【问题描述】:

我必须在退出时更新geoFence。为此,我需要当时的当前位置。

当我的应用关闭时我没有onLocationChanged 的监听器。并且为了 更新 geoFence 我需要我的位置。他们有什么方法可以在Geofence.GEOFENCE_TRANSITION_EXIT获得当前位置

public void broadcastUpdateGeoFences() {
        MainActivity.isGeoFenceAdded = false;//It tells to update geoFence
        Intent intent = new Intent(Constants.RECEIVER_GEOFENCE);
        intent.putExtra("done", 1);
        sendBroadcast(intent);
    }

MainActivity 中的广播接收器

   private BroadcastReceiver receiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                int resultCode = bundle.getInt("done");
                if (resultCode == 1) {

                    if(!MainActivity.isGeoFenceAdded){
                        updateGeoFencesOnCurrentExit();//I need current location here
                    }
                }
            }
        }
    };

一切正常。但是当应用关闭时,无法找到在退出时传递 currentLocation 的方法

private void updateGeoFencesOnCurrentExit(Location currentLocation){
            locationHandler.updateGeoFences(currentLocation);
}

【问题讨论】:

  • 您是否为此使用 Intent 服务?
  • 是的,我知道它应该是广播接收器
  • 您的实际添加地理围栏请求在哪里?

标签: android locationlistener android-geofence


【解决方案1】:

您可以在广播中实现 LocationListener 接口,并像这样使用覆盖方法 onLocationChanged

    @Override
public void onLocationChanged(Location location) {
    location.getLongitude();
    location.getLatitude();
}

【讨论】:

    【解决方案2】:

    我不建议在 IntentService 或 BroadcastReceiver 中使用 LocationListener,因为一旦函数(onHandleIntent 或 onReceive)退出,它们就会被销毁。一旦您获得地理围栏事件,我将使用带有 LocationManager 的 PendingIntent 来请求单个更新。我有示例应用程序来演示如何使用 github (https://github.com/pablobaxter/AndroidLocationExamples) 上的 PendingIntent 请求位置更新。

    编辑:

    仅供参考,IntentService 没有错。您只是在后台线程中运行 onHandleIntent 逻辑而不是在主线程中运行 onReceive

    【讨论】:

    • IntentService 不好,因为在 Android Oreo 上尝试从后台启动 IntentService 时会出现异常
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    • 2011-07-15
    • 2012-11-26
    • 2020-04-10
    相关资源
    最近更新 更多