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.
Once you press the back key the activity's onDestroy() method will be called and the activity will be flushed out of the memory. You will then be required to restart the activity by calling the startActivity() method which will in turn call its onCreate() Method.
Pressing Back Button from ActivityB Now when pressing back from ActivityB we land on ActivityA and this is the callback sequence: onPause – ActivityB. onRestart – ActivityA. onStart – ActivityA.
What is onBackPressed() in Android? This is an override function called when the user presses the back button on an Android device. It has great implications on the activity lifecycle of the application.
Activity-lifecycle concepts To navigate transitions between stages of the activity lifecycle, the Activity class provides a core set of six callbacks: onCreate() , onStart() , onResume() , onPause() , onStop() , and onDestroy() . The system invokes each of these callbacks as an activity enters a new state.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With