Sobes.tech
Junior — Middle

How is information exchanged between Fragment and Service using BroadcastReceiver?

sobes.tech AI

Answer from AI

Communication between Fragment and Service via BroadcastReceiver in Android occurs as follows:

  1. Service sends a broadcast message using sendBroadcast(Intent) or LocalBroadcastManager.
  2. Fragment registers a BroadcastReceiver that listens for specific actions in the intent.
  3. When the Service sends a broadcast, the registered BroadcastReceiver in the Fragment receives the Intent and processes the data.

Example:

// In Service
val intent = Intent("com.example.ACTION_DATA")
intent.putExtra("data", "Hello from Service")
sendBroadcast(intent)

// In Fragment
private val receiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        val data = intent?.getStringExtra("data")
        // Process the received data
    }
}

override fun onStart() {
    super.onStart()
    val filter = IntentFilter("com.example.ACTION_DATA")
    requireContext().registerReceiver(receiver, filter)
}

override fun onStop() {
    super.onStop()
    requireContext().unregisterReceiver(receiver)
}

This approach allows Service and Fragment to exchange data asynchronously and loosely coupled.