我正在 Android 14 设备上试验我的应用程序,我发送本地广播,然后在应用程序内订阅它。但是,当我使用
RECEIVER_NOT_EXPORTED
选项时,根本没有收到广播。
下面是我正在使用的代码:
class DashboardFragment : Fragment() {
private var \_binding: FragmentDashboardBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val dashboardViewModel =
ViewModelProvider(this).get(DashboardViewModel::class.java)
_binding = FragmentDashboardBinding.inflate(inflater, container, false)
val root: View = binding.root
binding.button.setOnClickListener {
Intent("com.nama.action").also { intent ->
intent.putExtra("nama", dashboardViewModel.text.value)
requireContext().sendBroadcast(intent)
}
}
val textView: TextView = binding.textDashboard
dashboardViewModel.text.observe(viewLifecycleOwner) {
textView.text = it
}
val br: BroadcastReceiver = MyBroadcastReceiver()
val filter = IntentFilter("com.nama.action")
ContextCompat.registerReceiver(requireContext().applicationContext, br, filter, ContextCompat.RECEIVER_NOT_EXPORTED)
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
当我用
RECEIVER_EXPORTED
跑步时,我能够接收广播。根据Google文档,我们不需要导出同一应用程序中使用的本地通知?
我在这里遗漏了什么吗?
对于具有自定义操作的意图,您需要在发送广播时指定包名称。
intent.setPackage(context.packageName)