Shared stuff across whole application in Android - java

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.

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.

Good Practice - Passing instance and call methods on instance

I would like to bounce something off you guys.
In my Mobile App, I have a lot of Activity and Fragment classes and many of them contain a method or two with code for uploading images to a WebAPI 2.0 web service etc. etc. Sorry, just for info.
Now, I thought about creating a new class (e.g. ServiceController) and then move all the Service Calls to this new class. The problem is, each one for the methods contain code for displaying a ProgressBar and hiding a ProgressBar, and let the activity continue to a next one, etc. etc.
Now, is it good practice to pass an instance of the Activity that is calling the method in the ServiceController to the method in the ServiceController and then for instance do this:
public static void uploadImages(Activity activity) {
new BaseAsyncTask() {
...
...
activity.hideProgressBar();
...
}
PS: Specifically the "activity.hideProgressBar();" above.
Thanks and have fun,
Pieter
There are many ways of decoupling between the classes , First of all service calls shouldn't be in the activity
first solution
1) Create one interface which contains onsuccess , onfailure abstract methods , and the parameters for that methods will be respective data model class types
2) The above interface should be implemented by activity which is dependent of data from server .In these implementation the showing and hiding progress bar , populating UI with data takes place
3)As you said ,Service Controller Instance will be created , while creating the instance of Service controller we have pass the reference of the interface . these interface is used for communication between service controller and activity.
second solution
Use Event Bus For Communicating between service controller and Activity
OTTO EVENT BUS i will prefer these .
Let me know if you have any queries , I Hope these will solve your problem.
third solution
use MVP Pattern Refer MVP Architecture Tutorial Best solution of all

Sending non serializable data from service to activity

Notify activity from service
I want to know if it is possible to do what the selected answer in the above post said, when your activity and service are in separate packages. Basically i have an object that is non-serializable (lets say a created view) and I want to send it from my service to my activity. Would be easy enough by using a custom binder, but as i've found out, you cant use custom binders when your service and activity are in separate packages.
I've been pondering this for a few weeks and it has really put a block in my project I am working on.
For those who will ask, I am trying to make a framework that allows "plugins" from other packages. But I am unsure how one would send non-serializable date back and forth between said service and activity.
It depends on the complexity of the object, If the object that you want to serialize is an object that comes from the Android SDK lets say a RelativeLayout or a Cursor I don't see that happening anyway, because those objects contains references to another objects that you don't have access to modify or make them implement the Serializable interface.
If your object is a class that you implemented and all references inside that class are also to another classes that you implementad (or to Serializable/Parceable objects) then sure you can. One way of doing so is, well, making them implement Serializable or making your own Parceable theres plenty of tools to achive this in a quick way like this or this one.
If no one of this answers satisfies you, then tell me what're you trying to send from the Service.
EDIT
Did you try to make a class implement both Serializable and OnClickListener and send it through the intent?
Sounds like you need some sort of Command pattern there.

implementing publish/subscribe in Android

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!

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?

Categories