Android 当应用程序不是 运行 时地理围栏停止工作

Android geofence stop working when app is not running

我正在开发一个使用 Google 地理围栏 API 的 Android 应用程序。 当应用程序处于前台时,我的代码似乎工作正常,但一旦应用程序进入暂停状态,地理围栏广播接收器就会停止接收事件。 我很确定当应用程序移至后台时地理围栏会被删除,但我不知道为什么会这样。

简而言之,我创建了一个地理围栏列表

Geofence geofence = new Geofence.Builder()
            .setRequestId(id)
            .setCircularRegion(lat, lng, GEOFENCE_RADIUS)
            .setExpirationDuration(Geofence.NEVER_EXPIRE)
            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_DWELL)
            .setLoiteringDelay(1000)
            .build();
        geofences.add(geofence);

然后我创建一个请求

geofenceRequest = new GeofencingRequest.Builder()
        .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_DWELL)
        .addGeofences(geofences)
        .build();

此时我添加地理围栏

LocationServices.GeofencingApi.addGeofences(googleApiClient, request, createGeofencePendingIntent()).setResultCallback(this);

最后我启动广播接收器

String GEOFENCE_ACTION = "gac.broadcast.geofence";
    if (geoFencePendingIntent != null)
    {
        GoogleApiClientManager.setGeofencePendingIntent(geoFencePendingIntent);
        return geoFencePendingIntent;
    }
    Intent intent = new Intent(GEOFENCE_ACTION);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), GEOFENCE_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    GoogleApiClientManager.setGeofencePendingIntent(pendingIntent);
    return pendingIntent;

正如我已经说过的,运行 在前台时一切正常,但一旦应用程序移动到后台,地理围栏事件就会停止发送到接收器。

ADDITIONAL INFOS(与广播接收器问题无关): 我尝试执行以下操作:

希望一切都清楚,并且有人可以帮助我。 提前致谢

实际上问题出在定义接收者意图上。

我变了

Intent intent = new Intent(GEOFENCE_ACTION);

Intent intent = new Intent(context, GeofenceBroadcastReceiver.class);

现在接收者在后台和前台都会收到通知。 希望这也能帮助到其他人。