SendBroadcast Intent Has Null Extras

3.2k Views Asked by At

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?

1

There are 1 best solutions below

2
On BEST ANSWER

You have to do:

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