简体   繁体   中英

Notifying view/activity when the data/model changes

I have an Activity A, Activity B and an Object C. I need to start Activity B from Activity A and while starting i need object C to find user location and once it is available Activity B must be notified with the location object.

I am not sure how Object C can notify Activity B since android dosent allow to get hold of Activity References.

Look into implementing a Bound Service . Your location info could be fetched within this service (on another thread, of course), and retrieved within Activity B when it binds to the service.

Use Java Observer and Observable classes.
By extending the Observable class on your data object (model), you are able to assign Observers which listen for changes in said data model. When the data changes, the Observer is notified automatically and fires its update() method.

The update() method is an obvious place to put your code which refreshes the views impacted by the changes in data, this is where the linkage between the views and the data model occurs (usually in the Android Activity). The beauty of using the Observer and Observable classes is that the data model, views and controller (the Activity that updates the views) are all separated. That is, you can use the data model for whatever you want, if you change the views it won't break the data model and vice versa. This makes your app much simpler to understand and easier to update later down the road.

Here's simple code example: http://www.ootpapps.com/eclipse_projects/ObserverExample.zip

Create an AsyncTask that will find the user location in the background.

Once completed, you can update the UI or maybe create a notification to the user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM