【问题标题】:SendBroadcast Intent Has Null ExtrasSendBroadcast Intent 有 Null Extras
【发布时间】:2014-05-30 15:15:16
【问题描述】:

我正在尝试使用 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)。

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

【问题讨论】:

    标签: android android-intent broadcastreceiver extras


    【解决方案1】:

    你必须这样做:

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

    【讨论】:

    • 有时您可能查看代码的时间过长......而错过了明显的内容。感谢您指出我不小心设置了错误的意图附加功能的错误!
    • 谢谢你,让我仔细检查了我的代码。 Intent broadcastIntent = new Intent(BROADCAST_INTENT); newOrgSet.putExtra("data", 123); LocalBroadcastManager.getInstance(getContext()).sendBroadcast(new Intent(BROADCAST_INTENT));我正在创建一个意图,添加一个额外的,然后创建另一个新的发送!
    猜你喜欢
    • 2014-11-16
    • 2014-03-01
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多