地理围栏事件并不总是被调用

Geofence events not always called

这是我添加地理围栏的方式:

public void setGeofenceRequest(Location location) {
    if (geofences == null) {
        geofences = new ArrayList<Geofence>();
    }
    geofences.add(new Geofence.Builder()
            .setRequestId("3")
            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_EXIT)
            .setCircularRegion(
                    location.getLatitude(), location.getLongitude(), PSLocationService.getInstance(context).kPSGeofencingDistanceMedium)
            .setExpirationDuration(Geofence.NEVER_EXPIRE)
            .build());
    Intent intent = new Intent(context, ReceiveTransitionsBroadcastReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    if (geofences.size() > 0) {
        LocationServices.GeofencingApi.addGeofences(mLocationClient, geofences, pi);
        Log.i("", "geof autopilot2 will set geofence for autopilot-3");
    }
}

这是我的 BroadcastReceiver。我应该在哪里接收它们:

public class ReceiveTransitionsBroadcastReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context ctx, Intent intent) {
    Log.i("","autopilot valid geof on receive transisionts broadcast receiver");
    PSMotionService.getInstance(ctx).buildGoogleApiClient();
    GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
    int transitionType = geofencingEvent.getGeofenceTransition();
    Location geofenceCenter = PSApplicationClass.getInstance().pref.getGeoCenter(ctx);
    if(geofencingEvent.getTriggeringLocation() != null) {
        if (geofenceCenter != null) {
            Utils.appendLog("GEOFENCE ENTERED ReceiveTransitionsBroadcastReceiver TRIGGERING LOCATION: " + geofencingEvent.getTriggeringLocation().toString() + " / GEOFENCE CENTER: " + geofenceCenter.getLatitude() + ", " + geofenceCenter.getLongitude(), "D", Constants.TRACKER);
        } else
            Utils.appendLog("GEOFENCE ENTERED ReceiveTransitionsBroadcastReceiver TRIGGERING LOCATION: " + geofencingEvent.getTriggeringLocation().toString(), "D", Constants.TRACKER);
    }else Utils.appendLog("GEOFENCE ENTERED ReceiveTransitionsBroadcastReceiver ERROR => TRIGGERING LOCATION NULL", "D", Constants.TRACKER);
    if(transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) {
        List<Geofence> triggerList = geofencingEvent.getTriggeringGeofences();
        for (Geofence geofence : triggerList) {
            Log.i("", "geof is s receive transition broadcast receiver " + transitionType + " GPS zone " + geofence.getRequestId());
            if(geofence.getRequestId().contentEquals("3")) {
                Log.i("", "geof autopilot2 ENTERED GEOFENCE will start pilot with first location");
                Utils.appendLog("GEOFENCE ENTERED ReceiveTransitionsBroadcastReceiver check to see if should start pilot", "T", Constants.TRACKER);
                PSLocationService.getInstance(ctx).fastGPS = -1;
                PSLocationService.getInstance(ctx).RequestLocationUpdates();
                if(PSTrip.getActiveTrip() != null) {
                    PSLocationService.getInstance(ctx).removeAutoPilotGeofence();
                }else PSMotionService.getInstance(ctx).checkinTime = System.currentTimeMillis() / 1000;
            }
        }
    }
}
}

现在通常可以,但并非总是如此。我会说只有大约 75% 的时间它应该工作,地理围栏事件实际上被调用了。我觉得自从我设置地理围栏以来的时间越长,它被调用的可能性就越小。 为什么会这样?当应用程序被垃圾收集器清理时,触发事件是否也被取消了? 我怎样才能让我的地理围栏在这种情况下总是被调用?

编辑:

这是我的默认配置:

 defaultConfig {
    minSdkVersion 15
    targetSdkVersion 23

    ndk {
        moduleName "ndkVidyoSample"
    }
}

我从广播接收器更改为 IntentService:

public class PSGeofenceTransitionsIntentService extends IntentService {
private static ActivityManager manager;
private static PSGeofenceTransitionsIntentService instance;
private GeofencingClient mGeofencingClient;
Context context;
private PendingIntent mGeofencePendingIntent;
public static boolean isMyServiceRunning(Class<?> serviceClass) {
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}
public static PSGeofenceTransitionsIntentService getInstance(Context context) {
    if (instance == null) {
        // Create the instance
        instance = new PSGeofenceTransitionsIntentService(context);
    }
    if (!isMyServiceRunning(PSGeofenceTransitionsIntentService.class)) {
        Intent bindIntent = new Intent(context, PSGeofenceTransitionsIntentService.class);
        context.startService(bindIntent);
    }
    // Return the instance
    return instance;
}
public PSGeofenceTransitionsIntentService() {
    super("GeofenceTransitionsIntentService");
}
public PSGeofenceTransitionsIntentService(Context context) {
    super("GeofenceTransitionsIntentService");
    mGeofencingClient = LocationServices.getGeofencingClient(context);
    manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    instance = this;
    this.context = context;
}
protected void onHandleIntent(Intent intent) {
    Log.i("", "autopilot valid geof on receive transisionts broadcast receiver");
    PSMotionService.getInstance(context).buildGoogleApiClient();
    GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
    int transitionType = geofencingEvent.getGeofenceTransition();
    Location geofenceCenter = PSApplicationClass.getInstance().pref.getGeoCenter(context);
    if (geofencingEvent.getTriggeringLocation() != null) {
        if (geofenceCenter != null) {
            Utils.appendLog("GEOFENCE ENTERED ReceiveTransitionsBroadcastReceiver TRIGGERING LOCATION: " + geofencingEvent.getTriggeringLocation().toString() + " / GEOFENCE CENTER: " + geofenceCenter.getLatitude() + ", " + geofenceCenter.getLongitude(), "D", Constants.TRACKER);
        } else
            Utils.appendLog("GEOFENCE ENTERED ReceiveTransitionsBroadcastReceiver TRIGGERING LOCATION: " + geofencingEvent.getTriggeringLocation().toString(), "D", Constants.TRACKER);
    } else
        Utils.appendLog("GEOFENCE ENTERED ReceiveTransitionsBroadcastReceiver ERROR => TRIGGERING LOCATION NULL", "D", Constants.TRACKER);
    if (transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) {
        List<Geofence> triggerList = geofencingEvent.getTriggeringGeofences();
        for (Geofence geofence : triggerList) {
            Log.i("", "geof is s receive transition broadcast receiver " + transitionType + " GPS zone " + geofence.getRequestId());
            if (geofence.getRequestId().contentEquals("3")) {
                Log.i("", "geof autopilot2 ENTERED GEOFENCE will start pilot with first location");
                Utils.appendLog("GEOFENCE ENTERED ReceiveTransitionsBroadcastReceiver check to see if should start pilot", "T", Constants.TRACKER);
                PSLocationService.getInstance(context).isLocationRequestsOn = -1;
                PSLocationService.getInstance(context).RequestLocationUpdates();
                if (PSTrip.getActiveTrip() != null) {
                    removeAutoPilotGeofence();
                } else
                    PSMotionService.getInstance(context).checkinTime = System.currentTimeMillis() / 1000;
            }
        }
    }
}
public void removeAutoPilotGeofence() {
    try {
        Log.i("", "autopilot remove autopilot geofence");
        List<String> list = new ArrayList<String>();
        list.add("3");
        if(mGeofencingClient == null)
            mGeofencingClient = LocationServices.getGeofencingClient(context);
        mGeofencingClient.removeGeofences(list).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Utils.appendLog("GEOFENCE removeAutoPilotGeofence Success removing geofences!", "I", Constants.TRACKER);
                Log.i("", "GEOFENCE removeAutoPilotGeofence Success removing geofences!");
                PSApplicationClass.getInstance().pref.setGeoCenterString(context, "-1");
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Utils.appendLog("GEOFENCE removeAutoPilotGeofence FAILURE removing geofences!" + e.getMessage(), "I", Constants.TRACKER);
                Log.i("", "GEOFENCE removeAutoPilotGeofence FAILURE removing geofences!" + e.getMessage());
            }
        });
        Utils.appendLog("GEOFENCE: Disabling geofence done removeAutoPilotGeofence", "E", Constants.TRACKER);
    } catch (final Exception e) {
        if (e.getMessage().contains("GoogleApiClient") && e.getMessage().contains("not connected")) {
            PSLocationService.getInstance(context).startLocationClient();
            Handler han = new Handler();
            han.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Utils.appendLog("autopilot2 error will try again", "E", Constants.TRACKER);
                    removeAutoPilotGeofence();
                }
            }, 1000);
        }
        Log.i("", "autopilot2 error replaceFragment autopilot geofence:" + e.getMessage());
        Utils.appendLog("autopilot2 error replaceFragment autopilot geofence:" + e.getMessage(), "E", Constants.TRACKER);
    }
}
public void setGeofenceRequest(final Location location) {
    ArrayList geofences = new ArrayList<>();
    geofences.add(new Geofence.Builder()
            .setRequestId("3")
            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_EXIT)
            .setCircularRegion(
                    location.getLatitude(), location.getLongitude(), PSLocationService.kPSGeofencingDistanceMedium)
            .setExpirationDuration(Geofence.NEVER_EXPIRE)
            .build());
    //ADDING GEOFENCES
    if (geofences.size() > 0) {
        if(mGeofencingClient == null)
            mGeofencingClient = LocationServices.getGeofencingClient(context);
        mGeofencingClient.addGeofences(getGeofencingRequest(location, geofences), getGeofencePendingIntent()).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                RealmLocation realmLocation = new RealmLocation(location.getLatitude(), location.getLongitude(), location.getTime() / 1000, null, true);
                realmLocation.setAccuracy(location.getAccuracy());
                realmLocation.setSpeed(location.getSpeed());
                PSApplicationClass.getInstance().pref.setGeoCenter(realmLocation, context);
                Utils.appendLog("GEOFENCE setGeofenceRequest Success adding geofences!" + location.getLatitude() + " / " + location.getLongitude(), "I", Constants.TRACKER);
                Log.i("", "GEOFENCE setGeofenceRequest Success adding geofences! " + location.getLatitude() + " / " + location.getLongitude());
                PSLocationService.getInstance(context).stopLocationClient();
                PSMotionService.getInstance(context).buildGoogleApiClient();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Utils.appendLog("GEOFENCE setGeofenceRequest FAILURE adding geofences!" + e.getMessage(), "I", Constants.TRACKER);
                Log.i("", "GEOFENCE setGeofenceRequest FAILURE adding geofences!" + e.getMessage());
            }
        });
        Log.i("", "geof autopilot2 will set geofence for autopilot-3");
    }
}
/**
 * Gets a PendingIntent to send with the request to add or remove Geofences. Location Services
 * issues the Intent inside this PendingIntent whenever a geofence transition occurs for the
 * current list of geofences.
 *
 * @return A PendingIntent for the IntentService that handles geofence transitions.
 */
private PendingIntent getGeofencePendingIntent() {
    // Reuse the PendingIntent if we already have it.
    if (mGeofencePendingIntent != null) {
        return mGeofencePendingIntent;
    }
    Intent intent = new Intent(context, PSGeofenceTransitionsIntentService.class);
    // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling
    // addGeofences() and removeGeofences().
    return PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
/**
 * Builds and returns a GeofencingRequest. Specifies the list of geofences to be monitored.
 * Also specifies how the geofence notifications are initially triggered.
 */
private GeofencingRequest getGeofencingRequest(Location location, ArrayList<Geofence> geofences) {
    GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
    // The INITIAL_TRIGGER_ENTER flag indicates that geofencing service should trigger a
    // GEOFENCE_TRANSITION_ENTER notification when the geofence is added and if the device
    // is already inside that geofence.
    builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_EXIT);
    // Add the geofences to be monitored by geofencing service.
    builder.addGeofences(geofences);
    // Return a GeofencingRequest.
    return builder.build();
}

}

我也有删除和添加地理围栏的代码,并且监听器总是进入关于添加它们的 onSuccess。

首先,我不会将这段代码放在 BroadcastReceiver 中。

除了不良做法之外,组件可能会在代码执行完毕之前关闭。

如果您需要 运行 可能需要一些时间的代码,请考虑从您的 Receiver 启动 Service。 否则对于较短的执行时间,您可以使用 IntentService.

通过查看您的代码,我知道您的地理围栏未按预期工作的两个原因:

1) 地理围栏的性质

Geofences API 主要通过 WiFi / 蜂窝数据检索您的位置,这通常不可用。

我曾尝试使用地理围栏,但发现它们非常不准确。我切换到 LocationManager 使其使用纯 GPS 位置并且它符合我的期望。

请参阅 this answer,建议

Poll the GPS hardware on an interval without doing anything with the result and you'll start getting more accurate geofences.

我从未尝试过 Google 的 FusedLocation API,但我听说有人说它对他们非常有效。

如果您使用 LocationManager,则必须自己实施 'Geofencing logic';您可以使用 Location.distanceTo(Location).

轻松完成

示例:

final float distanceFromCenter = currentLocation.distanceTo(this.destination);

if (distanceFromCenter <= YOUR_RADIUS_IN_METERS) {
   // you are inside your geofence
} 

2) CPU 未激活

地理围栏处于活动状态这一事实并不一定意味着您的 phone 处于清醒状态并正在计算位置检查。

要解决此问题,您可以从 BroacastReceiver 启动 ForegroundService。该服务也应包含 partial WakeLock。 这保证:

  1. OS 不会终止服务(或者更好:被终止的机会更少...)
  2. 用户知道该服务,必要时可以关闭
  3. CPU是运行宁。因此您可以确定获取位置的代码是运行ning(请记住在服务停止时释放WakeLock)。

请注意,Android 可能仍会在必要时终止您的服务。

您可以在网上找到大量关于如何从 BroadcastReceiver 启动 ForegroundService、如何保持 WakeLock 等的示例...

此外,请查看新的 Android O API,它对 ForegroundService 和其他组件进行了一些小改动。

PS: 我已经开发和应用了上面提到的所有组件(除了 FusedLocation),我非常满意。

编辑:回答 OP 的问题

好吧,这里还是尽量整理一下吧,不然后面的读者很容易搞糊涂。我将首先回答原始问题和 'bounty banner' 中写的内容,然后是 OP 编辑​​,最后是 OP 在评论中提出的问题。

1) 原题

Is the triggering event also being dismissed, when the app is cleaned by the garbage collector?

很可能是的。请参阅 ,其中 OP 在单独的进程中实现了一项服务 运行,以便即使在应用程序被终止时也能触发地理围栏。

I need to understand what causes the geofences not to get called, if enough time has passed

很多原因。看我原来的回答。

I saw an implementation of the geofence logic with an Service instead of a broadcast receiver, will that work better?

接收器和服务是两个不同的东西。请阅读 Android 的文档。您可以从 BroadcastReceiver 启动服务,这通常是 'receive' PendingIntents 的首选方式并对其进行处理。

2) 编辑

  • 请注意,我并没有告诉您用服务替换 BroadcastReceiver,但从您的接收器启动服务并在那里处理您的所有逻辑可能是个好主意。
  • 将您的 IntentService 设为 Singleton class 没有必要,因为(来自 IntentService documentation

All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.

  • 不要将 Context 存储到 Singleton class 或一些静态引用中。我印象深刻 Android Studio 没有警告你。

3) 评论

I need this to work 24/7 hence I cannot use the location all the time, cause of obvious battery issues.

请阅读Android Oreo Background Execution Limits。这对您来说可能是个问题。

Also now that I changed to a intentService, is that enough to ensure it should stay awake?

不,正如我所说,您可能需要部分 WakeLock 才能打开 CPU。

Do I need to initiate it another way, in order to keep it in the foreground?

是的。为了启动前台服务,您需要调用 startForeground(int, Notification)

请注意:IntentServices 的生命周期仅限于 onHandleIntent() 函数的末尾。通常,它们的寿命不应超过几秒钟。如果要启动前台,请使用服务 class。

此外,如原始答案中所述,新的前景 API 可用并且是 Android Oreo 的首选。

Not a question, just a notice: I need to use here Geofencing. (Geofencing will start if necessary the gps

好的,完美。看看什么最适合你。