implementing publish/subscribe in Android - java

Currently, I am working on an extensible sensing and data processing framework for Android device. This framework will enables a wide range of data signals (e.g., location, wifi, battery, accelerometer) via Android mobile device.
I consider that these data signals are publishers, which publish data. Classes that extends Activity (public class MainActivity extends Activity) are subscribers.
I believe that an ideal way of implementing this functionality is to implement a small publish/subscribe middleware in between publishers and subscribers.
Can you please suggest -- How can I implement publish/subscribe middleware on Android device ? For me, the main issue is -- how the MainActivity class can register itself for getting events and how various data signals notify to many regitered MainActivity class? Please note this middleware does not need advance features like communication over network.

Somebody did it for you http://square.github.io/otto/. Use this framework or check the sourcecode.

Think about an example this way:
SomeFragmentA - this fragment defines an interface with methods in it
SomeFragmentB - this also defines an interface with methods in it
MainActivity - this activity registers for updates from the above fragments
Now, the activity will be listening for events by simply implementing the interfaces from those two fragments and doing whatever it wants.
In this situation, when the fragment publishes anything new, it does that through a call to its method and passes back the arguments as needed.
try{
((YourInterFaceListetener) activity).someMethod(arguments);
}catch(ClassCastException cce){
Log.d(cce.getMessage());
}
Doing this creates that easy communication between the other parts of the app with an activity and you can extend it by simply implementing required interfaces.
Good luck!

Related

Communication between objects, broadcastreceivers and services

I have made this app that offers it's functionality almost completely in a notification. The configuration is done in the app itself. This is the structure I have now:
Service 1: retrieve data and changes to that data from FireBase and save it in an object. Everything the app needs to show in the app itself is in this object. It gets distributed to other activities via the observable pattern. So these activities implement Observer.
Service 2: this service keeps track of external changes that can directly affect the object in service 1. Therefore, this service is bound to service 1.
Activities: some activities to display the data. All these activities implement Observer and observe the object that's stored in Service 1.
So far so good. The above gives me no problems whatsoever. I can communicate with both services from every activity. Every activity gets an update if the object they are interested in changes and figures out what to do with the updated data.
Now I have this notification, all of it's actions are broadcasted intents, for which I have a BroadcastReceiver that handles these intents. The broadcastreceiver may need data from Service 1 to execute it's action, and all actions are located in simple classes (no activity or service), but I can't bind a broadcastreceiver or objects to a service.
As I see it I have 2 possible solutions here:
Create another service in which all possible "notification" actions are located. This service can be bound to Service 1 and thus can retrieve all the data it needs.
Make the observable object in Service 1 static, so even the objects in which the "notification" actions are located can access it.
Possible problems for solution 1: maybe 3 services is a little over-kill? But putting all functionality in the same service would create a big, unclear service.
Possible problems for solution 2: I've read that static variables are not best practice, because static variables represent global state and are hard to reason about. Source
I hope someone can tell me if I'm right on the above assumptions, and if there's a solution I have not mentioned here.

Calling third part class method

I have class A (extends Activity) which present a list of items from a table.
In class B (which extends activity) i am calling a method which eventually trigger class C (C extends a broadcast receiver).
In my class C i am updating a table in my DB in which class A gets the items to present.
My question is how to invoke a class A method after class C finish updating the table.
Making class A function static is quite impossible in this case.
If class C extends BroadcastReceiver and it is responsible for updating your database, once you update you can send a new Broadcast to let other parts of your application know that the table update is finished. You will need to register a receiver in the places you want to get the notification (i.e. in your A Activity class). If you only need to broadcast locally (only to your Application) you can use the new LocalBroadcastManager provided by the v4 support library. It will only broadcast locally and get rid of IPC overhead.
Activities generally can't call methods from other activites. You need to find a different way for communicating between those classes. For example instantiate a dynamic receiver via registerReceiver() in the one activity and send a broadcast in the other.
Apart from that, your questions seems to indicates your application architecture is not optimal. There is always only one activity visible at a time. Why do your activities need to communicate with each other?

Shared stuff across whole application in Android

I'm not asking about repairing my code or something I've just have a problem on where to or how to put methods in proper places in my application.
I wrote an application enhancing bluetooth chat - I made service for this bluetooth chat that runs in background. I will have more such services. Basically I want to be able to run methods across whole my application:
send message via bluetooth chat and wait for answer,
scan RFID tag with NFC,
scan Barcode with camera,
etc.
Each of this I know how to do in 1 activity easily. Now I'm looking for a solution to put this in something like a global class that will allow me to call this methods across my whole application - so I don't have to initialize anything but just - doSomething() and it does it.
Where should I put such things:
in custom activity class (all my other activities will use it)?
in application?
something else?
The same applies to handlers. Basically as to bluetooth chat you have to make handler to listen to received messages - where to put it as well.
I'm basically looking for propositions on how to solve this.
You can have one BaseActivity that extends activity and put your common functions in BaseActivity, now extend all other activities with BaseActivity.
Your activity will have these functions available.
For example:
class BaseActivity extends activity{
...........
public void sendMsgViaBluetooth(String msg){
...........
}
}
class MyActivity extends BaseActivity{
<OnSomeEvent>{
sendMsgViaBluetooth(msg);
}
}
I would create a class with some static methods that allows you to obtain instances of certain classes handling different functionality. You can create a listener system where multiple activities can register themselves for events, such as received messages. When the main class then receives something, it will go through all listeners, and inform them.
Otherwise, you can also send broadcasts, and let those activities interested listen for them. A problem here though is that no one is listening, messages might be lost. When you handle it yourself, in case no one is listening you can store messages in a queue, and send them when new listeners register.
I would not go with the BaseActivity idea. The bigger your app gets, the harder this becomes (e.g., what if you want a Fragment to do things as well, a service that should obtain something, or when you want to implement other classes that require to extend anything else than Activity).
To have data/methods that "follows" you all over the scope of your application, create a Class that extends Application. You have to specify in your Manifest that this Class will be your Application class.
android:name="com.example.MyApplicationClass">
After that, you can call getApplication() to get the Application context and cast it to your Class
myAppContext = (MyApplicationClass)getApplication();
Try avoiding Singleton pattern. I've done one in an application and when the app became big enough, my singleton would get erased sometimes (when resuming the application after coming back from launcher). The application context is supposed to keep the data even if the application is in background for a long time.

One connection shared between two fragments

I started to write my first mature Android application and I stuck...
I want to implement tablet view easily to I used android compatibility library v4 and fragments API. Everything was cool until I created network connection and share it beetween two fragments. You know, I have two views...
Let's assume that we have simple chat application and we need to have user list and messages list. I need to implement those both fragments depending from message received from network. So if someone is entering chat I need to update userlist fragment and if someone send new message I need to send it to messages fragment
Could anyone tell me how to do it?
Any ideas how to update both fragments with one connection.
Thanks in advance
You should have a separate CommunicationManager Class which handles all the sending & receiving - the fragments only display the information you need - all the communication logic is in this one class. Then you will have no problems with your app logic anymore.
As far as I understood you want to use one network connection (saying generally), receive a response and again display it in two different fragments.
There are some patterns you can follow to do that, but here are some suggestions to solve your problem.
Try to use the standard Android pattern where you will have:
A class for Networking. (keep it in background or executorthread)
A clsss for Repository. (It will be used to fetch the data from the Networking class). When you instantiate the Networking.class in Repository.class use a Singleton Pattern so that only one instance of Networking.class is used across the whole app which will let you to use one Networking.class to fetch all the data you need without instantiating Networking.class again.
As #Zakaria suggested, use the Android View model pattern
A One ViewModel class will be enough to use the Repository.class in it to receive data from the Networking class and share the data (Observe data) in your fragments and show your required data to user.
That's it, it will solve you problem.

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)
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.

Categories