Android - Share location info between activities
What is the best practice to share Location info between activities? For example:
- Activity1 (main) displays data based on user current location (lat&long)
- Activity2 displays a google map with data near to current location of user
- Activity3 displays开发者_StackOverflow中文版 calendar events near to current location of user
Each acivity will call specific webservice method by sending current location.
I'm asking this because I'm confused:
- should I create a static reference of Location object (get the user location in the main activity) and use that object in other activities.
- each activity to have its own implementation to get user location.
Thank you
If you want the location to stay constant as you navigate the activities, pass it in on the starting intent and just have each activity maintain a copy of the data.
If, on the other hand, you want to have the location dynamic in all 3, I would look into making a service to listen to the location service. Your activities can then bind to that service and receive updates. This ensures you don't wind up with multiple listeners floating around and accidentally keep the Location Listeners alive longer than desired. It also gives you a single place to maintain any settings necessary (i.e. user opt out, frequency and precision, etc).
Its quite easy to pass information from one activity to another. When you create an intent that you use to start another activity you can attach additional information to that intent that the new activity has access to when it starts up.
Here is an example:
To pass information from one Activity to another you can do:
Intent i = new Intent(this, OtherActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("variableName", "variable value");
Then in the other Activity you would do the following
Bundle extras = this.getIntent().getExtras();
String var = null;
if (extras != null) {
var = extras.getString("variableName");
}
You can pass more than just Strings, ints, etc... you can even pass objects. Objects that are children of the Parcelable class can be passed as well. To add the parcelable to the intent simply:
i.putExtra("variableName", instanceOfMyClass);
In the new Activity you would simply call:
MyClass obj = (MyClass) extras.getParcelableExtra("parcelableName");
精彩评论