问题描述
我正在尝试在 Android 11 上将广播从 App A 发送到 App B。
这是接收方应用 B:
清单:
code
接收器类:
<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>
这是发送方应用 A:
清单:
class TestReceiver: broadcastReceiver() {
override fun onReceive(context: Context?,intent: Intent?) {
Log.d("MY_TAG","received: ${intent?.getIntExtra("data",0)}")
}
}
发件人代码(在 <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
如果有人知道我哪里出错了,请帮忙。如果不可能,有没有其他方法可以将数据从一个应用程序传递到另一个应用程序?谢谢。
解决方法
解决了。以下是几点:
- 在应用 B(接收方)中,还需要在清单顶部的
<permission>
标签中声明权限。我错过了这个。 -
Category
不是必需的。也无需在sendBroadcast()
中声明权限
- 应用 A(发送方)中的
<uses-permission>
是必需的。 -
ComponentName
或包名称(使用setPackage()
)需要在 Android 11 中提及。
这是更正后的代码:
这是接收方应用 B:
清单:
<permission android:name="com.example.my_test.broadcast_permission"/>
...
<application>
...
<receiver android:name="com.example.my_test.TestReceiver"
android:permission="com.example.my_test.broadcast_permission">
<intent-filter>
<action android:name="com.example.my_test.receive_action"/>
</intent-filter>
</receiver>
...
</application>
...
接收器类:无变化。
这是发送方应用 A:
清单:无变化
发件人代码(在 MainActivity
内):
findViewById<Button>(R.id.button).setOnClickListener {
val intent = Intent("com.example.my_test.receive_action")
intent.component = ComponentName("com.example.my_test","com.example.my_test.TestReceiver")
// if exact receiver class name is unknown,you can use:
// intent.setPackage("com.example.my_test")
intent.putExtra("data",69)
sendBroadcast(intent)
}