Intent使用LocalBroadcastManager按类别过滤

时间:2014-11-28 09:25:07

标签: android android-intent intentfilter localbroadcastmanager

我跟随geofencing guidelines,我无法获得LocalBroadcastManager类别工作的意图。 Intent发送者发送2种具有相同类别GeofenceUtils.CATEGORY_LOCATION_SERVICES的Intent:

- 行动GeofenceUtils.ACTION_GEOFENCES_ADDED

Intent broadcastIntent = new Intent();
String msg;
broadcastIntent.setAction(GeofenceUtils.ACTION_GEOFENCES_ADDED)
               .addCategory(GeofenceUtils.CATEGORY_LOCATION_SERVICES)
               .putExtra(GeofenceUtils.EXTRA_GEOFENCE_STATUS, msg);
LocalBroadcastManager.getInstance(mActivity).sendBroadcast(broadcastIntent);

- 行动GeofenceUtils.ACTION_GEOFENCE_ERROR

Intent broadcastIntent = new Intent();
String msg;
broadcastIntent.setAction(GeofenceUtils.ACTION_GEOFENCE_ERROR)
               .addCategory(GeofenceUtils.CATEGORY_LOCATION_SERVICES)
               .putExtra(GeofenceUtils.EXTRA_GEOFENCE_STATUS, msg);
LocalBroadcastManager.getInstance(mActivity).sendBroadcast(broadcastIntent);

在收件人中,我希望有一个IntentFilter按类别过滤意图而非按行动过滤:

geofenceReceiver = new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {
    // Get extra data included in the Intent
    String message = intent.getStringExtra(GeofenceUtils.EXTRA_GEOFENCE_STATUS);
    Log.d(TAG, "geofenceReceiver got message: " + message);
}

IntentFilter intentFilter = new IntentFilter();
intentFilter.addCategory(GeofenceUtils.CATEGORY_LOCATION_SERVICES);
LocalBroadcastManager.getInstance(this).registerReceiver(geofenceReceiver, intentFilter);

但永远不会触发onReceive。为什么?

1 个答案:

答案 0 :(得分:0)

好的,我在http://developer.android.com/reference/android/content/IntentFilter.html找到了解决方案:

  

匹配基于以下规则。请注意,要使IntentFilter与Intent匹配,必须包含三个条件:操作和类别必须匹配,并且数据(数据类型和数据方案+权限+路径,如果指定)必须匹配(有关数据字段如何匹配的详细信息,请参阅match(ContentResolver,Intent,boolean,String)。

     

如果任何给定值与Intent操作匹配,则操作匹配;如果过滤器未指定任何操作,则它仅匹配不包含操作的Intents。

     如果Intent中的所有类别都与过滤器中给出的类别匹配,则

类别匹配。过滤器中不在Intent中的额外类别不会导致匹配失败。请注意,与操作不同,没有类别的IntentFilter只会匹配没有任何类别的Intent。

所以我必须将Action添加到IntentFilter

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(GeofenceUtils.ACTION_GEOFENCES_ADDED);
intentFilter.addAction(GeofenceUtils.ACTION_GEOFENCE_ERROR);
intentFilter.addCategory(GeofenceUtils.CATEGORY_LOCATION_SERVICES);