Search code examples
androidandroid-serviceobserver-pattern

Android - Can an activity and a service communicate using the Observer design pattern or similar?


Is it possible to make an activity and a service communicate, using the Observer design pattern? I want to make them communicate both ways by giving them both the role as Observer and Notifier The reason why I want to do this, is that I want low coupling between them. So if the activity crashes for some reason, the service will still be running and still trying to notify the GUI without crashing. The reason I want the service to remain running, is that it acts like a server in a LAN and I still want the system and the clients to communicate even when the GUI of the server is gone.

If this can't be achieved using the Observer pattern or is too complex, is there another way to achieve what I described above?

Thanks in advance


Solution

  • You can run the service as foreground if your are using notification . so when the activity exit the service can update with the notification or remote views.

    Also , When you start the activity you can bind the service from the activity to communicate using service connection.

             bindService(new Intent(this,
                YourService.class), mConnection, Context.BIND_AUTO_CREATE);
    

    A started service can use the startForeground(int, Notification) API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory. (It is still theoretically possible for the service to be killed under extreme memory pressure from the current foreground application, but in practice this should not be a concern.)

    check the link - http://developer.android.com/reference/android/app/Service.html http://developer.android.com/guide/components/bound-services.html