Intent Filter by category with LocalBroadcastManager

716 views Asked by At

I'm following geofencing guidelines and I can't get LocalBroadcastManager for intents with categories working. Intent sender sends 2 kinds of Intents with the same category GeofenceUtils.CATEGORY_LOCATION_SERVICES:

-with action 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);

-with action 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);

In receiver I'd like to have an IntentFilter which filters Intents by category not by action like so:

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);

But onReceive is never triggered. Why?

1

There are 1 answers

0
Marian Paździoch On BEST ANSWER

OK I found the solution here http://developer.android.com/reference/android/content/IntentFilter.html:

A match is based on the following rules. Note that for an IntentFilter to match an Intent, three conditions must hold: the action and category must match, and the data (both the data type and data scheme+authority+path if specified) must match (see match(ContentResolver, Intent, boolean, String) for more details on how the data fields match).

Action matches if any of the given values match the Intent action; if the filter specifies no actions, then it will only match Intents that do not contain an action.

Categories match if all of the categories in the Intent match categories given in the filter. Extra categories in the filter that are not in the Intent will not cause the match to fail. Note that unlike the action, an IntentFilter with no categories will only match an Intent that does not have any categories.

So I have to add both Actions to the IntentFilter:

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