I'm experimenting with my app on an Android 14 device, where I'm sending a local broadcast and then subscribing to it within the app. However, when I utilize the RECEIVER_NOT_EXPORTED
option, the broadcast is not being received at all.
Below is the code that I am using:
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
}
}
When I run with the RECEIVER_EXPORTED
I am able to receive the broadcast. According to the Google docs, we do not need to export the local notifications that are used in the same app?
Am I missing something here?
For intents with custom action you need to specify package name when sending broadcast.
intent.setPackage(context.packageName)