广播接收器将错误数据从一个 activity 发送到另一个 activity

Broadcast receiver sends wrong data from one activity to another activity

我想在一个 activity 中扮演另一个角色。让我们称它们为 SenderReceiver。所以,在 Receiver 我已经注册了接收者:

receiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                val command = intent.getIntExtra("action_id", -1)
                val bundle = intent.extras

                for (key in bundle!!.keySet()) {
                    val value = bundle[key]
                    Timber.i(String.format("%s %s (%s)", key,
                            value.toString(), value!!.javaClass.name))
                }

            }
        }

registerReceiver(receiver, IntentFilter("command"))

我在关闭之前从`Sender activity发送数据:

backToMess.setOnClickListener {
            dialog.dismiss()

            val intent = Intent()
            intent.action = "command"
            intent.putExtra("action_id", 1)
            intent.putExtra("m_id", intent.getIntExtra("message_id", 0))
            intent.putExtra("list_type", intent.getIntExtra("list_type", 0))
            intent.putExtra("list_pos", intent.getIntExtra("list_pos", 0))
            sendBroadcast(intent)

            finishAndRemoveTask()
        }

我从 Sender 发送的数据是:1,9238,1,12 我在 Receiver 收到的数据是:1,0,0,0 我不明白为什么会这样。也许我不能发送几个额外的东西?

I send from Sender is: 1,9238,1,12

val intent = Intent()
intent.getIntExtra("message_id", 0)

您正在从刚创建的对象中读取数据,该对象为“0”。

尝试

   backToMess.setOnClickListener {
        dialog.dismiss()

        val broadcastIntent = Intent()
        broadcastIntent.action = "command"
        broadcastIntent.putExtra("action_id", 1)
        broadcastIntent.putExtra("m_id", intent.getIntExtra("message_id", 0))
        broadcastIntent.putExtra("list_type", intent.getIntExtra("list_type", 0))
        broadcastIntent.putExtra("list_pos", intent.getIntExtra("list_pos", 0))
        sendBroadcast(broadcastIntent)

        finishAndRemoveTask()
    }