70

I been struggling a lot thinking about where to place Android Services in the new Android recommended Architecture. I came up with many possible solutions, but I cannot make up my mind about which one is the best approach.

I did a lot of research, and I couldn't find any useful guideline nor tutorial. The only hint I found about where to place the Service in my app architecture is this one, from @JoseAlcerreca Medium post

Ideally, ViewModels shouldn’t know anything about Android. This improves testability, leak safety and modularity. A general rule of thumb is to make sure there are no android.* imports in your ViewModels (with exceptions like android.arch.*). The same applies to presenters.

According to that, I should place my Android Services on the top of my Architecture Components hierarchy, at the same level as my Activities and Fragments. That's because Android Services are part of the Android framework, so ViewModels shouldn't know about them.

Now, I will explain briefly my scenario, but only to make the panorama clearer, not because I want an answer for this specific scenario.

  • I have an Android Application that has a MainActivity with many fragments in it, all of them tied together in a BottomNavBar.
  • I have a BluetoothService bound to myActivity and one of its fragments (because I want the Service to have the same lifecycle as the Activty but I also want to interact with it directly from my fragment).
  • The fragment interacts with the BluetoothService to get two types of information:
    • Information about the state of the Bluetooth connection. Doesn't need to be persisted.
    • Data that comes from the Bluetooth Device (it is a Scale, so weight and body composition in this case). Needs to be persisted.

Here are the 3 different architectures I can think of:

LiveData inside AndroidService LiveData inside Android Service arch

  • The LiveData with the state of the connection and with the weight measurements coming from the Bluetooth Device are inside the BluetoothService.
  • The Fragment can trigger operations in the BluetoothService (scanDevices for example)
  • The Fragment observes the LiveData about the state of the connection and adapts the UI accordingly (for example, enable a button if the state is connected).
  • The Fragment observes the LiveData of the new weight measurements. If a new weight measurement comes from the BluetoothDevice, the Fragment then tells its own ViewModel to save the new data. It is done via a Repository class.

Shared ViewModel between fragment and AndroidService Shared ViewModel arch

  • The Fragment can trigger operations in the BluetoothService (scanDevices for example)
  • The BluetoothService updates the Bluetooth related LiveData in the shared ViewModel.
  • The Fragment observes the LiveData in its own ViewModel.

Service ViewModel Service ViewMOdel arch

  • The Fragment can trigger operations in the BluetoothService (scanDevices for example)
  • The BluetoothService updates the Bluetooth related LiveData in its own ViewModel.
  • The Fragment observes the LiveData in its own ViewModel and the BluetoothService ViewModel.

I am pretty sure I should place them on top of the architecture and treat them just like an Activity/Fragment, because BoundServices are part of the Android Framework, they are managed by the Android OS and they are bound to other Activities and Fragments. In that case, I don't know what's the best way to interact with LiveData, ViewModels and Activities/Fragments.

Some might think that they should be considered as a DataSource (since in my case it's getting data from a scale using Bluetooth), but I don't think this is a good idea, because of all what I've said in the previous paragraph and specially because of what it says here:

Avoid designating your app's entry points—such as activities, services, and broadcast receivers—as sources of data. Instead, they should only coordinate with other components to retrieve the subset of data that is relevant to that entry point. Each app component is rather short-lived, depending on the user's interaction with their device and the overall current health of the system.

So, finally, my question is:

Where should we place our Android (Bound) Services and what is their relation with the other architectural components? Is any of these alternatives a good approach?

dglozano
  • 4,658
  • 2
  • 12
  • 31
  • 1
    You can assume your service as '*lifecycle aware component*' in **MVVM**. How? You already have **bounded service**, bind it to *lifecycle owner*(in your case activity and one fragment you're binding to) and during any resume or start event of your lifecycle observer(you service here), call or notify your data change to your lifecycle owner. so all you need is implement `LifecycleObserver` interface. – Jeel Vankhede Nov 29 '18 at 13:56
  • 1
    @JeelVankhede that's a nicer way of managing the binding and unbinding of my Service that I hadn't considered, thanks! However, I can't still understand how this will end up working in relation with my ViewModel and LiveData issue. You would place the Ble related LiveData in the Fragment's ViewModel? How to notify changes in between? Because the data is not available onStart or onResume, it is gathered in between. – dglozano Nov 29 '18 at 18:37
  • 1
    @MartinZeitler when referring other sites, it is often helpful to point that [cross-posting is frowned upon](https://meta.stackexchange.com/tags/cross-posting/info) – gnat Nov 30 '18 at 08:34
  • 1
    I'm voting to close this question as off-topic because this it belongs to https://softwareengineering.stackexchange.com – Martin Zeitler Nov 30 '18 at 15:57
  • @gnat just thought so, because I've linked to another answer there, in the comments of my retracted answer... and since this question is not directly related to code, it appears to be off-topic. there it might even receive better answers than on here. so far it is not yet a cross-post, but should be migrated. – Martin Zeitler Nov 30 '18 at 16:04

5 Answers5

42

Updated:

After getting suggestion from @Ibrahim Disouki (Thank you for that) I dig deeper and found out something interesting! Here's background.

O.P. seeks for solution "Where Service component of Android Framework stands considering Android Architecture Components". So, here's out the box(SDK) solution.

It stands at the same level as Activity/Fragment. How? If you're extending Service class though rather than that, start extending LifecycleService. Reason behind that is simple that previously we had to rely on Activity/Fragment lifecycle in order to receive updates/do some contextual operations on Service. But now it's not the case.

LifecycleService now has it's own lifecycle registry/maintainer called ServiceLifecycleDispatcher which takes care of lifecycle of service which also makes it LifecycleOwner.

It leaves us in condition that from now on, You can have a ViewModel to LifecycleService doing operations for itself & if you're following proper app architecture and having repository pattern leaves you to single source of truth!

In context of O.P. LifecycleService now can have ability to maintain it's ViewModel to do business logic related to repository layer, and later on another lifecycle aware component like, Activity/Fragment can also consume/reuse same ViewModel to have their specific operations to it.

Please note that by doing so, you're in state of having two different LifecycleOwners (Activity & LifecycleServie) which means you can't share view models between LifecycleService & other lifecycle aware components. If you don't like approach then be good with old callback kind of approach having callbacks back to Activity/Fragment from service when data is ready to serve etc.


Obselete:

(I suggest not to read through)

In my opinion, Service should be on same level as Activity/Fragment, because it's Framework component & not MVVM. but because of that Service doesn't implements LifecycleOwner and it's Android Framework Component, it shouldn't be treated as data source because it can be entry point to application.

So, dilemma here is that sometimes (In your case), Service acts as data source which provides data from some long running task to UI.

So what it should be in Android Architecture Component? I think you can treat it as LifecycleObserver. because, no matter what you do in background, you'll need to consider about lifecycle of the LifecycleOwner.

Why? because, we usually do bind it to LifecycleOwner (Activity/Fragments) & to do long running tasks off the UI. So, it can be treated like LifecycleObserver. In such a way we made our Service as "Lifecycle aware component" !


How you can implement it?

  1. Take your service class and implement LifecycleObserver interface to it.

  2. When you bind your service to Activity/Fragment, during your service connection of your service class, add your service to your activity as LifecycleObserver by calling method getLifecycle().addObserver(service class obj)

  3. Now, Take an interface in service class to provide callback from service to your UI and every time your data changes, check that if your service has at least on Lifecycle event create or resume to provide callback with.

In such a way, we won't require LiveData to update to from service and even no ViewModel (Why do we need it for service? We don't need configuration changes to survive on service lifecycle. And main task to VM is that to consist data between lifecycles).


Side Note: If you think you're having long running background operations, then consider using WorkManager. After using this library, you'll feel like Services should be marked as deprecated by now! (Just a random thought)

Jeel Vankhede
  • 8,541
  • 2
  • 18
  • 46
  • Thanks, so far it's the best answer I think :) However, I won't mark it as the correct just yet. It is true that the service is in charge of retrieving some, but it is also keeping track of the connection status with the device. The fragment enables/disables some buttons on the UI depending on the connection status. This is something that should survive a rotation of the screen, for example. Therefore, the BluetoothService is storing that connection status in a LiveData Object and the fragment observes it to react accordingly. How would you handle that? – dglozano Nov 30 '18 at 13:01
  • Then about the other type of information that the BluetoothService handles, the retrieving of data, I agree with what you say :) Just to clarify, you propose that: the Activity has a reference to the Service and trigger different operations in it, and then the Service doesn't have a reference to the activity, but instead communicates the arrival of a new bunch of data using the observer pattern? Is that right? – dglozano Nov 30 '18 at 13:04
  • Yes, for your `LiveData` purpose, use the same `ViewModel` of your Activity/Fragment & communicate with it using Interface callbacks to and forth to your service. You can use transformation map on livedata for that purpose. – Jeel Vankhede Nov 30 '18 at 13:06
  • I see your point. And what would be the pros and cons of doing that (Activity/Fragment triggers operations to Service, Service answer with callbacks, Activity/Fragment updates the related LiveData in its own ViewModel) with using a "Shared viewModel" between the Service and the Activity/Fragment? So the data doesn't go from the Service to the Activity and from there to thew ViewModel, but directly from the Service to the ViewModel – dglozano Nov 30 '18 at 16:09
  • 3
    No from my point, don't use shared VM or LiveData for service. We've made our service lifecycleObserver meaning that it's now aware of activity/fragment. So , use direct callback by respecting lifecycleOwner States. No need to use mediator for service now. – Jeel Vankhede Dec 02 '18 at 04:30
  • 2
    Service is now implementing LifecycleOwner check [LifecycleService](https://developer.android.com/reference/androidx/lifecycle/LifecycleService?hl=en) but now the question is how do I create a shared view model between service and another Android component like Activity or Fragment? @JeelVankhede – Ibrahim Disouki Jun 27 '20 at 12:30
  • 2
    @IbrahimDisouki Frankly, I answered this long ago but now as you're referring that service is `LifecycleOwner` which means my answer doesn't make sense in that case, I'll need to think through it again and come up with solution. All I can say is that there's only one way you can share data is by following conventional communication we used to do in past between any activity and service. – Jeel Vankhede Jun 27 '20 at 12:36
  • 2
    Does anyone have a working code example of this answer? – Emi Raz Jul 01 '20 at 13:53
  • 1
    @JeelVankhede can you please help me initializing my ViewModel. I need ViewModelStore or ViewModelStoreOwner for initializing ViewModel with ViewModel.Factory. But extending LifecycleService doesn't provide ViewModelStore. Do I need to implement this? If so, what should be the overridden function? – Mihodi Lushan Sep 23 '20 at 20:52
  • You should reference the newer solution right at the top of the answer so people don't waste their time with the older, no longer up-to-date solution and use the new approach instead. – Emil S. Oct 14 '20 at 13:09
  • 1
    @EmilS. Sorry for your inconvenience, updated the post. Thanks for your feedback. – Jeel Vankhede Oct 15 '20 at 09:21
  • @JeelVankhede I missed the point here. Why do you talk about life cycle when the problem is how to pass data to activities / fragments? A bound Service exists as long as there is a client that can interact with it, so it is sufficient to manage the binding and unbind in the appropriate activity / fragment lifecycle state. That said, the problem of the OP remains and it is how to properly manage the data between services and activities / fragments. – blow Apr 03 '21 at 13:50
  • @blow Either you are confused mate after going through my answer or else You might have not read through question yet. It's been long since I answered this question and O.P. was basically seeking help on understanding what is the best place for services in MVVM pattern. There was never issue about data passing/communication issue in this post as O.P. already knows how to deal with that. My answer was clearly trying to come up to any conclusion on architecture pattern for services in android. If you've some better thoughts, let me know we can always discuss and agree upon something. – Jeel Vankhede Apr 05 '21 at 09:16
1

One way to avoid direct contact with an Android service while still being able to use it is through an interface object. This is part of the "I" for Interface Segregation in the acronym, SOLID. Here is a small example:

public interface MyFriendlyInterface {
    public boolean cleanMethodToAchieveBusinessFunctionality();
    public boolean anotherCleanMethod();
}

public class MyInterfaceObject implements MyFriendlyInterface {
    public boolean cleanMethodToAchieveBusinessFunctionality() {
        BluetoothObject obj = android.Bluetooth.nastySubroutine();
        android.Bluetooth.nastySubroutineTwo(obj);
    }

    public boolean anotherCleanMethod() {
        android.Bluetooth.anotherMethodYourPresentersAndViewModelsShouldntSee();
    }
}

public class MyViewModel {
    private MyFriendlyInterface _myInterfaceObject;

    public MyViewModel() {
        _myInterfaceObject = new MyInterfaceObject();
        _myInterfaceObject.cleanMethodToAchieveBusinessFunctionality();
    }
}

Given the above paradigm, you are free to place your services in a package that's outside your packages that contain POJO code. There is no "right" location to put your services -- but there are definitely WRONG places to put them (e.g. where your POJO code goes).

Grant Park
  • 904
  • 1
  • 8
  • 26
1

What if we bind/unbind to/from service from activity or multiple activities as usual in onStart/onStop, then we have singleton instance that holds Bluetooth related manager (I use nordic lib for ble manager) . That instance is in service so that we can disconnect for example when service is destroyed because ui unbound from it and reconnect to ble when service is created. We also inject that ble manager singleton into viewmodel to make interaction and data listening easier via livedata or rx or similar reactive data provided by ble manager, for example for connection state. This way we can interact from viewmodel with ble, subscribe to characteristics etc and service is there to provide scope that can survive over multiple activities and basically knows when to connect or disconnect. I have tried this approach in my app and so far it works ok.

Sample project https://github.com/uberchilly/BoundServiceMVVM

uberchilly
  • 151
  • 1
  • 7
  • This solution seems interesting to me, but what if no one starts the service for you? Basically you only depend on the ble manager but it only works if you start a specific service. How do the activities/fragments know this? – blow Apr 03 '21 at 07:29
0

In my opinion using LiveData in servise is comfortable

    class OneBreathModeTimerService : Service() {
        var longestHoldTime = MutableLiveData<Int>().apply { value = 0 }
        ...
    }

Then in fragment

     override fun onCreate(savedInstanceState: Bundle?) {
         mServiceConnection = object : ServiceConnection {

            override fun onServiceConnected(name: ComponentName, binder: IBinder) {
                mOneBreathModeService = (binder as OneBreathModeTimerService.MyBinder).service

                mOneBreathModeService!!.longestHoldTime.observe(this@OneBreathModeFragment, androidx.lifecycle.Observer {
                    binding.tvBestTime.text = "Best $it"
                })
            }

            override fun onServiceDisconnected(name: ComponentName) {}
     }

I am not pro in LiveData, but what can be wrong with such approach?

brucemax
  • 413
  • 4
  • 10
-2

How about treating your service like this?

enter image description here

M-WaJeEh
  • 16,562
  • 9
  • 59
  • 93
  • 2
    I think OP mentioned a requirement for the service to be bound to Activity to get the Activity lifecycle... OP probably doesnt want to kill battery scanning and observing bluetooth if not relevant. – MidasLefko Nov 27 '18 at 08:30
  • 2
    Hmmm this was my first thought. However, I feel BluetoothService is not like a webservice. It is an android component, with its own lifecycle and it is managed by Android OS. It also needs to be started passing a Context. So I do not think it can be down there. Moreover, what would be the Responsibility of "Ble Data Source"? Also, if you look the architecture from top to down, the deeper you go the more "far" you are from Android, until you "leave it completely" when you reach SQL or your API. With BluetoothService, that doesn't happen, and it feels weird. – dglozano Nov 27 '18 at 11:08
  • 1
    To make a parallelism, in my opinion, the equivalent of SQLite or a webservice in my scenario would be the GattServer inside my Scale. The interaction with it is handled by the Bluetooth Service, so in that sense would be the equivalent of a DAO. So everything seemed to make sense, until I read JoseAlcerreca post. – dglozano Nov 27 '18 at 11:18
  • 1
    Also, from Android Dev's Guide: Avoid designating your app's entry points—such as activities, services, and broadcast receivers—as sources of data. Instead, they should only coordinate with other components to retrieve the subset of data that is relevant to that entry point. Each app component is rather short-lived, depending on the user's interaction with their device and the overall current health of the system. – dglozano Nov 27 '18 at 11:19