简体   繁体   中英

How to access a variable from any class or service to another class or activity?

I want to show user a simple info or value on a activity that is updated from a service.

public static Long Count = 0L; 
/*Timer -> Count++;*/

Above variable is stored in the service and changed based on events or timer. But I can not find a way to access its updated value and show it when the app is open.

I have tried static and getter and setters, LiveData, and data Class with single Instance. All attempts failed. Binding service is not an option since it requires to run without activity.

So can anyone tell me a way (if exist) to access this or any similar variable with updated value from any class or service to another class or activity?

You can use GreenRobot. By using this feature, you can access/send data to any class/activity from anyone. Green Robot Event Bus

I would recommend you follow the Repository pattern as explained by Android here to keep a hold of your currently static variable and bring in an instance of this Repository wherever you need to use it again.

You can use the StateFlow :

val _count = MutableStateFlow(0L)
val count = _count.asStateFlow()

// post updates on _count
_count.value = <something else>

Then in the opened activity:

lifecycleScope.launch {
    count.collect {
        // update the UI
        view.setText(it.toString())
    }
}

Edit:

To bind the service to the activity instead of using static variables or singletons, use Binder provided by Android.

That takes care of the multiple instances of activity/service and doesn't create a cyclic references.

Note that collect will only trigger if the value changed is distinct ie if value is set to a value that previously ot contained, the collector won't be triggered

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM