2

I am trying to send a message from an IntentService to an Activity using a BroadcastReceiver. Here is my code in the IntentService:

/**
 * Received a message from the Google GCM service.
 */
@Override
protected void onMessage(Context context, Intent intent) {

    Log.e(TAG, "Got a new message from GCM");

    // create the intent
    Intent broadcastIntent = new Intent(BROADCAST_NOTIFICATION);
    intent.putExtra("name", "Josh");
    intent.putExtra("broadcasting", true);
    sendBroadcast(broadcastIntent);
}

In the Activity class, I register a receiver to listen for these messages:

private class IncomingTransmissionReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // if we are looking at a broadcast notification
        if (intent.getAction().equals(GCMIntentService.BROADCAST_NOTIFICATION)) {

            // are we broadcasting?
            boolean broadcasting = intent.getBooleanExtra("broadcasting", false);

            // get the name of the person who is broadcasting
            String name = intent.getStringExtra("name");

            Log.e(TAG, "Got a message, broadcasting= "+ broadcasting + " name= " + name);
        }
    }
}

When I send the broadcast, this is what is printed by the log:

Got a message, broadcasting= null name= null.

Even intent.getExtras().getString("name") and intent.getExtras().getBoolean("broadcasting") return null (intent.getExtras() also returns null).

What am I doing wrong? Why are my intent extras null when I obviously set them?

Joshua W
  • 4,973
  • 5
  • 24
  • 30

1 Answers1

4

You have to do:

    // create the intent
    Intent broadcastIntent = new Intent(BROADCAST_NOTIFICATION);
    broadcastIntent.putExtra("name", "Josh");
    broadcastIntent.putExtra("broadcasting", true);
    sendBroadcast(broadcastIntent);
greywolf82
  • 21,813
  • 18
  • 54
  • 108
  • Sometimes you can be looking at the code too long... and miss the obvious. Thanks for pointing out my mistake of accidentally setting the wrong intent extras! – Joshua W May 30 '14 at 15:33
  • Thanks for this, made me double check my code properly. `Intent broadcastIntent = new Intent(BROADCAST_INTENT); newOrgSet.putExtra("data", 123); LocalBroadcastManager.getInstance(getContext()).sendBroadcast(new Intent(BROADCAST_INTENT));` I was creating an intent, adding an extra, and then creating another new one to send! – Glenn.nz Nov 17 '15 at 05:56