My application calls a few web services when it is freshly launched. I would also like to call these web services if the user launches the app (which was running in the background) and resumes. I've looked into all the methods fired when apps are launched and when activities are in focus. onStart(), onResume(), onRestart() etc....
I thought onRestart would be a good bet to make my web service calls and update my view, problem is if I go from activity A (the one making the calls) to activity B and hit the back button, activity A will fire onRestart() and call the web services. I don't want this to happen everytime I go back to my main screen from some activity in my app. I only want the services to be called if my app activity A is brought into focus from the outside. Are their any other events I should be aware of that could help me? If I hit the home button and then hit my app icon it should update, but not if I click something on my main screen, opening a new activity and then hit the back button.
Hope the question makes sense.
Thanks.
According to the Activity lifecycle, onRestart
will be called before onResume
. So if you put your web calls in onResume
, it will be called when the activity first starts and any time it resumes. onRestart
is only called when the user navigates back to that activity. So you can have a boolean in your activity (ex. boolean isActivityRestarting) that is set to false, then set to true in onRestart
. If it's true when onResume
is hit, then don't do your web calls.
Example code:
public void onRestart() {
isActivityRestarting = true;
}
public void onResume() {
if (!isActivityRestarting) {
executeWebCalls();
}
isActivityRestarting = false;
}