尝试实现 Android 共享表,并遵循官方文档。该表出现并且共享按预期进行。然而,广播接收器永远不会触发。这是代码:
活动课中:
// convenience method to create the sheet
var shareSheetIntent = shareSheetIntent(
shareSheetTitleId = R.string.share_sheet_title,
shareSheetImageId = R.drawable.ic_sheet_logo,
messageToShare = messageText
)
val pendingIntent = PendingIntent.getBroadcast(
this,
4321,
Intent(this, MyShareSheetReceiver::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
).intentSender
shareSheetIntent = Intent.createChooser(shareSheetIntent, null, pendingIntent)
startActivity(shareSheetIntent)
然后这是我的接收器:
class MyShareSheetReceiver : BroadcastReceiver() {
override fun onReceive(p0: Context?, p1: Intent?) {
Log.d("hello", "share sheet receiver fired")
}
}
除了接收器之外的所有东西都可以工作。消息被发送到预期的收件人,但我没有看到
onReceive
被触发。我错过了什么?
编辑:
检查logcat,我可以看到这条消息:
收到广播意图 0x80a4d6 Key{broadcastIntent pkg=com.example.debug 意图=cmp=com.example.debug/com.example.MyShareSheetReceiver 标志=0x2000000 u=0} requestCode=4321 从 uid 1000 发送=0
我想回答我自己的问题,因为我相信 Android 文档遗漏了一个非常重要的细节。
我通过将接收器类添加到清单中解决了这个问题。在如何向其他应用程序发送数据(以及如何使用广播接收器获取回调)的文档中,没有任何地方提到必须添加到清单中。
具体来说,这是我所做的:
<receiver
android:name="com.example.MyShareSheetReceiver"
android:exported="false"
android:enabled="true"/>
在 BroadcastReceivers 的一般文档中,讨论了使用上下文来注册接收器,但这似乎与共享表接收器不兼容,因为使用了 IntentFilter、不同的标志等。尽管如此,共享表接收器似乎是一个上下文注册的接收者,这应该使得在清单中注册它是不必要的。
因此,对于可能遇到同样问题的其他人,请尝试一下。希望它能为您解决问题。它对我有用。