Home > database >  How to send data by Intent from BroadcastReceiver to Fragment in Kotlin
How to send data by Intent from BroadcastReceiver to Fragment in Kotlin

Time:01-04

I will send step count:

Foreground Service -> Broadcast Receiver -> Fragment

Since I need to keep tracking step count on background and when app is off, I've created two Broadcast Receiver, one for notification to keep showing step count on background and one for fragment UI which will be unregistered on Destroy.

So this process is for the latter.

  1. Foreground Service

: I send "stepCount" value to broadcast.

   Intent().also { intent ->
        intent.setAction(ACTION_STEP_COUNTER_NOTIFICATION)
        intent.putExtra("stepCount", "$todayTotalStepCount")
        sendBroadcast(intent)
    }
  1. BroadcastReceiver

    open class StepCountBroadcastReceiver : BroadcastReceiver() {

     override fun onReceive(context: Context?, intent: Intent?) {
         super.onReceive(context, intent)
    
         if(intent!!.action == ACTION_STEP_COUNTER_NOTIFICATION) {
             var intent = Intent()
             var stepCount = intent.getStringExtra("stepCount")
    
             var sendMyDiary = Intent(context!!, MyDiaryFragment::class.java)
             sendMyDiary.putExtra("stepCount", stepCount)
             context.startActivity(sendMyDiary)
         }
     }
    

    }

when custom Action is triggered, this will get 'stepCount' from Service and here I will send it to Fragment named MyDiaryFragment.

So I send it by using Intent().putExtra.

  1. Fragment
    private val stepCountBroadcastReceiver: BroadcastReceiver = StepCountBroadcastReceiver()

        val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION).apply {
            addAction(ACTION_STEP_COUNTER_NOTIFICATION)
        }
        LocalBroadcastManager.getInstance(requireActivity()).registerReceiver(stepCountBroadcastReceiver, filter)

Here is my question. I register this StepCountBroadcastReceiver in onCreate.

But I don't know how to get stepCount coming from broadcast in Fragment whenever Broadcastreceiver is called.

It that same process like just adding this below line at the bottom?

var stepCount = requireActivity().intent.getStringExtra("stepCount")

    val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION).apply {
        addAction(ACTION_STEP_COUNTER_NOTIFICATION)
    }
    LocalBroadcastManager.getInstance(requireActivity()).registerReceiver(stepCountBroadcastReceiver, filter)
    var stepCount = requireActivity().intent.getStringExtra("stepCount")

CodePudding user response:

In your broadcast receiver, add this.To Send a LocalBroadCast

override fun onReceive(context: Context?, intent: Intent?) {
     super.onReceive(context, intent)

     if(intent?.action == ACTION_STEP_COUNTER_NOTIFICATION) {
         var stepCount = intent.getStringExtra("stepCount")
         var localBroadCastIntent = Intent(LOCAL_BROADCAST_KEY)
         localBroadCastIntent.putExtra("stepCount",stepCount?:"") 
         Handler(Looper.getMainLooper()).post {
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
        }
     }
 }


const val LOCAL_BROADCAST_KEY = "step_counter_local_broadcast"

In your Fragment Call this register function.And in onCreateView and make sure to call unregisterReceiver in ondestroyview of Fragment.

    private fun registerBroadCastReceiver() {
LocalBroadcastManager.getInstance(applicationContext).registerReceiver(
                receiver,
                IntentFilter(LOCAL_BROADCAST_KEY)
            )
        }
    }

Add this BroadCast Receiver,in Fragment Class globally.

 private var receiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            intent?.let {
                val stepCount = it.getStringExtra("stepCount")
            }
        }
    }

Note:

Here Flow will be like this.

Service -> BroadCast Receiver -> LocalBroadCastReceiver -> UpdateFragment UI.

You can also directly call this localbroadcast from service based on your usecase. So it will be like below.

Service-> LocalBroadCastReceiver -> UpdateFragment UI.

So only when fragment is alive, the local broadcast receiver will receive messages and update ui.

  • Related