【发布时间】:2018-05-17 21:34:31
【问题描述】:
当应用停止运行时,来自 Google 的新地理围栏 API 不会触发任何事件。我尝试使用PendingIntent.getBroadcast() 和PendingIntent.getService(),但只能在应用打开时获取转换事件。
我遵循了代码实验室的 this 教程,但修改了代码以使用新的 GeofencingClient
更新
这就是我创建待处理意图的方式:
private PendingIntent getGeofencePendingIntent() {
if (mGeofencePendingIntent != null) {
Log.d(TAG, "Pending intent is already there");
return mGeofencePendingIntent;
}
Log.d(TAG, "Creating a new pending intent");
// In case I'm using Service, the second parameter will be GeoIntentService.class
Intent mIntent = new Intent(mContext, GeoReceiver.class);
// In case I'm using Service, the method will be getService(...)
mGeofencePendingIntent = PendingIntent.getBroadcast(mContext, 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT);
return mGeofencePendingIntent;
}
我的 GeoReceiver 的 onReceive 方法中的代码。不知何故,在onHandleIntent 方法中使用服务时,代码是相似的
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive");
if (intent == null) {
Log.e(TAG, "Intent is null");
return;
}
final String action = intent.getAction();
if (ACTION_ADD_GEOFENCE.equals(action)) {
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()) {
String errMsg = GeofenceExceptionMessages.getErrorString(context, geofencingEvent.getErrorCode());
Log.e(TAG, "onReceive Error: " + errMsg);
return;
}
int geofenceTransition = geofencingEvent.getGeofenceTransition();
if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
NotificationHelper helper = new NotificationHelper();
String geofenceTransitionDetails = helper.getGeofenceTransitionDetails(
context,
geofenceTransition,
triggeringGeofences
);
helper.sendNotificaiton(context, geofenceTransitionDetails);
Log.i(TAG, "onReceive: " + geofenceTransitionDetails);
}
} else {
Log.d(TAG, "Diffirent Action: " + action);
}
}
【问题讨论】:
-
您能否发布设置您的 IntentService 和 IntentService 本身的代码?
-
@ThomasStevens 请检查更新
-
GeoReceiver 类扩展了 IntentService?
-
@ThomasStevens 不,我的 GeoReceiver 扩展了 BroadcastReceiver 和 GeoIntentService 扩展了 IntentService
-
IntentService 是一个专门用于在您的应用程序处于后台(或前台)时运行短任务的类,当您的应用程序处于后台时,广播接收器不会接收任何内容,IntentService 会。
标签: android geofencing android-geofence google-location-services