Reputation: 1969
I am trying to solve the following problem: I am writing an application that has multiple activities that share data model. The data is fetched from DB when application starts and saved as global variables in Application class extension as follow:
class MyApp extends Application {
private MyData myData;
public MyData getData(){
return myData;
}
public void setData(MyData d){
myData = d;
sendBroadcast(new Intent("DATA_UPDATED"););
}
}
The AndroidManifest.xml is updated of course and everything works great - every activity can read the data and update it, other activities can get notifications of data change using the BroadcasrReceiver. Things get problematic when I have another thread that should update the main (GUI) thread: I have a service that contains a callback when new data is received from the db. the callback is running on new thread, so updating my Apllication data model must being done on the main thread. for that I used handler as follow:
public void ServiceCallback(...newData) {
//Pass the message up to our handler to make the update on the main thread.
Message receipt = Message.obtain(mHandler, 0, newData);
receipt.sendToTarget();
}
//Handle incoming message from remote on the main thread (GUI thread)
private Handler mHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
//read new data from the message - from msg.obj field, no prob.
//but - how can i get to my application model instance????
}
};
So i though passing it exactly as I passed the new_data in the message, but I saw in this post
that it may lead to memory leak...? I didnt understand if its true and why, and maybe I have another solution that anyone can suggest? I would really appreciate it. Is it possible to use broadcast receivers between threads? maybe this is my solution?
Upvotes: 0
Views: 629
Reputation: 52936
It is a bit unclear what exactly you are trying to do. A few things to note: using an application object for shared/global data doesn't really buy you anything. You can simply use a singleton. If you want to use the Application
, you can add a static getInstance()
method to it, since there is only one instance it is by definition a singleton, adding the method will simply make it easier to access from non-activity classes. You don't have to update data in the Application
class on the main thread. You only need to do things on the main thread when you are dealing with the UI.
Additionally, if you simply want to send a message to another thread, a Handler
is sufficient. There is no need to involve BroadcastReceivers
.
Upvotes: 1