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????
}
};
但我看到「https://stackoverflow. com/ questions/4481928和roid-getting-activity-instance- in- in-application- from- handler」,
我不知道它是否真实,为什么,也许我还有另一个解决办法,谁可以建议呢?我真的很感激。能否在线间使用广播接收器?也许这就是我的解决方法?