Home > front end >  Kotlin: How to read MutableLiveData in Background
Kotlin: How to read MutableLiveData in Background

Time:01-04

I created MutableLiveData<Int> in order to keep tracking step count.

  companion object {
        var todayTotalStepCount: MutableLiveData<Int>? = MutableLiveData()
    }

And I use ForegroundService to make SensorManager keep working in background or even when app is off.

In Service() class, I use NotificationManager and I want this notification keep noticing mutable step count.

    private fun secondNoti(stepCount: Int?) {
        Log.d("결과1", "$todayTotalStepCount")
        Log.d("결과2", "$stepCount")


        if (Build.VERSION.SDK_INT >= 26) {
            val CHANNEL_ID = "my_app"
            val channel = NotificationChannel(
                CHANNEL_ID,
                "MyApp", NotificationManager.IMPORTANCE_DEFAULT
            )
            (getSystemService(NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(
                channel
            )
            val notification = NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_logo)
                .setContentTitle("${todayTotalStepCount?.value} 걸음")
                .setColor(ContextCompat.getColor(this, R.color.main_color))
                .build()
            startForeground(1, notification)
        }
    }
}

So as you can see above, I tried to show this value as title with below line.

.setContentTitle("${todayTotalStepCount?.value} 걸음")

However It shows null.

I print todayTotalStepCount on log, and it says:

 androidx.lifecycle.MutableLiveData@759014c

I tried to read this MutableLiveData value by using observe.

  todayTotalStepCount?.observe(viewLifecycleOwner) { value ->
        receivedStep = value
    }

But It can't define viewLifecycleOwner.

enter image description here

So My question is how can I read this MutableLiveData value in Notification which runs on background as separate function.

I'm a newbie in Kotlin, So please help me with detail code.

Thank you!

CodePudding user response:

You shouldn't use global static variable for this type of data, because it's not being shared between different app instance, and easy to be reseted to null if the app is cleared

My suggestion is define your custom BroadcastReceiver to transfer data between your Service and the main app, which is well-documented in here

1/ Define your own BroadcastReceiver class

class CurrentStepCountReceiver : BroadcastReceiver

2/ Register your receiver in Manifest

<receiver android:name=".CurrentStepCountReceiver" android:exported="false">
    <intent-filter>
        <action android:name="your.package.name.currentstepcountreceiver" />
    </intent-filter>
</receiver>

3/ Do your logic in onReceived() in CurrentStepCountReceiver

override fun onReceive(context: Context, intent: Intent) {
    // Retrieve the step count via intent data
    // Show your notification here
}

4/ When your ForegroundService get new sensor data, pass the data to the Intent and use sendBroadcast to wake up any registered receiver, which is now your code inside onReceived

Intent().also { intent ->
    intent.setAction("your.package.name.currentstepcountreceiver")
    intent.putExtra("step_count", newStepCount)
    sendBroadcast(intent)
}

Hope this helps

  • Related