Reputation: 147
What is the best practice to share Location info between activities? For example:
Each acivity will call specific webservice method by sending current location.
I'm asking this because I'm confused:
Thank you
Upvotes: 3
Views: 959
Reputation: 20319
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");
Upvotes: 0
Reputation: 2336
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).
Upvotes: 3