SendBroadcast意图有空的额外

时间:2014-05-30 15:15:16

标签: android android-intent broadcastreceiver extras

我正在尝试使用BroadcastReceiver从IntentService向Activity发送消息。这是我在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);
}

在Activity类中,我注册了一个接收器来监听这些消息:

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

当我发送广播时,这是日志打印的内容:

收到消息,broadcast = null name = null。

甚至intent.getExtras()。getString(" name")和intent.getExtras()。getBoolean(" broadcast")返回null(intent.getExtras()也返回null )。

我做错了什么?当我明显设置它们时,为什么我的意图为空?

1 个答案:

答案 0 :(得分:4)

你必须这样做:

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