android - SendBroadcast Intent 具有空额外内容

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

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

收到消息,广播= null name= null。

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

我做错了什么?为什么我明明设置了 Intent 附加项却为空?

最佳答案

你必须做:

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

关于android - SendBroadcast Intent 具有空额外内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23957886/

相关文章:

Android 开放 Intent ://protocol in WebView

android - 隐式广播接收器未调用

android - 牛轧糖中的互联网连接

java - 无法创建广播接收器android

android - 尝试膨胀自定义 viewpager android

android - Mobiscroll 的问题 - orientationchange 和 access address bar 会导致一些移动浏览器崩溃

android - Google home 如何以编程方式获取特定 wifi 的密码?

android - BroadcastReceiver 尝试在无序广播期间返回结果 - Android 中的 PACKAGE_ADDED