【发布时间】:2021-02-21 20:07:31
【问题描述】:
我正在尝试在 Android 11 上将广播从应用 A 发送到应用 B。
这是接收器应用 B:
清单:
<receiver android:name="com.example.my_test.TestReceiver"
android:enabled="true"
android:permission="com.example.my_test.broadcast_permission">
<intent-filter>
<action android:name="com.example.my_test.receive_action"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
接收器类:
class TestReceiver: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
Log.d("MY_TAG", "received: ${intent?.getIntExtra("data", 0)}")
}
}
这是发件人应用 A:
清单:
<uses-permission android:name="com.example.my_test.broadcast_permission"/>
...
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
...
发件人代码(MainActivity 内):
findViewById<Button>(R.id.button).setOnClickListener {
val intent = Intent("com.example.my_test.receive_action")
intent.addCategory("android.intent.category.DEFAULT")
intent.component = ComponentName("com.example.my_test", "com.example.my_test.TestReceiver")
intent.putExtra("data", 69)
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
sendBroadcast(intent, "com.example.my_test.broadcast_permission")
}
这是我迄今为止所尝试的一切。也不确定这里是否有任何关于广播许可的错误。没有任何效果,TestReceiver 类从不记录任何内容。
我也试过android:exported="true"
如果有人知道我在哪里犯了错误,请提供帮助。如果不可能,有没有其他方法可以将数据从一个应用程序传递到另一个应用程序?谢谢。
【问题讨论】:
标签: android broadcastreceiver android-broadcast android-11