Issue
When my activity starts, I start a service that fetches data then sends it back to the activity so it can update the UI.
If a config change occurs:
- If I already have the fetched data, I save it in the
onSaveInstanceStatemethod. - If I haven't received the fetched data, I want to cancel the running service and relaunch it using the new activity.
So my onSaveInstanceState currently looks like this:
@Override
public void onSaveInstanceState (Bundle outState) {
if (data != null) {
outState.putSerializable(DATA_IN_BUNDLE, data);
}
// Stop any data fetching that may be going on.
stopService(new Intent(this, FetchService.class));
}
However, I've noticed that this method is called during the normal starting of the activity, which I didn't know happened, so when it's run the service is always cancelled.
So my questions are:
- Is this documented somewhere? Couldn't find anywhere that said
onSaveInstanceStateis called during activity start. - What would a better place to stop the service be?
onConfigurationChanged?
Thanks!
Solution
You have a few choices:
Don't allow Android to kill and restart your
Activity. Manage the config changes yourself. Usually this is pretty simple to do and prevents you from having to deal with stopping and restarting background stuff.Pass the
ServiceConnection(or whatever you are using as a communication channel to theService) from the oldActivityinstance to the newActivityinstance by usingonRetainNonConfigurationInstance()andgetLastNonConfigurationInstance()Use a service-bus architecture, so that one
Activitycan start something and anotherActivitycan register for the callback.Send the response from the
Serviceto theActivityusing a broadcastIntent, which can be seen by the newActivityafter a config change.
Answered By - David Wasser
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.