Ryan
Ryan

Reputation: 3619

Android MVC design patterns

I am looking for some design patterns to use controlling a set of Activitys in an Android application. I am currently developing an app which I feel will go under many many revisions of the UI until its "final" release (if there ever is one). I was thinking something along the lines of an Observer pattern using a controller in the Service but I can't find any good examples. The only thing I find common references to is using AIDL for inter-process interface binding, which will not be applicable.

Basically what I want is for the Activity to implement a defined Interface such as showLoginScreen(), loginError() etc. such that ANY UI should be able to implement (the controller is not tied directly to the view, only its interface). If this is the cleanest way to accomplish this, what is the best accepted way of getting handles to active Activitys? I have always been confused what happens when you invoke a method on an Activity that is not active.

I was thinking something along the lines of a Map in the Application class serving as a singleton? The put() / remove() of the Map would be tied to onStart() and onPause(). This still doesn't guarantee the Activity is still alive though...a reference could be gained with a get() on the key, and then it could be paused() before the Service has a chance to call its interface.

Any suggestions or insight would be appreciated.

edit: I have looked at other posts such as MVC pattern on Android however they mostly don't address implementation (and that accepted answer I just flat out disagree with anyways)

Upvotes: 0

Views: 1959

Answers (1)

Noel
Noel

Reputation: 7410

To use an observer/observable pattern between your activities and your service, you will need to use Bound services.

This way, you can get a handle to the IBinder which can act as your Observable and you do not have to worry about AIDL. You can ensure that the Service has been bound to in the onServiceConnected() method in your ServiceConnection. Keep in mind that your service will only be alive as long as there is an Activity bound to it, otherwise it will be stopped.

I would recommend reading the android Bound Services documentation as it explains the usage very well.

Upvotes: 1

Related Questions