I need to do some network request when user restores my app from background (for example: worked with app - pressed home button - home screen - switched to my app again via task manager or clicked app icon). I don't want this to be triggered by screen rotate or simple change of current activity by startActivity(). What is the best approach?
Override the onResume() method.
#Override
public void onResume() {
super.onResume();
//Your work goes here
}
onResume() will be called when the user returns to the Activity.
Related
I am testing my android app that is in development.
It contains a single MainActivity
I noticed through testing that onDestroy was being called every time I push the back button.
I thought that this was weird. So I created a fresh empty activity app using android studio, and added no code. Just a simple hello world.
Even in this hello world app, onDestroy is being called everytime I press back.
I am running a Samsung S4 and I have not reason to believe that it is resource starved. What is going on here?
I tried setting android:launchMode to all available values in AndroidManifest.xml, and none of that worked....
Activity getting destroyed whenever you are pressing back button i.e android default behavior. This is how code flows.
override onBackPressed inside your Activity
/**
* called when user press back button on device
*/
#Override
public void onBackPressed() {
super.onBackPressed();
}
Go inside onBackPressed which lies inside FragmentActivity which shows that it will first pop all fragments from activity and then it will finish activity.
/**
* Take care of popping the fragment back stack or finishing the activity
* as appropriate.
*/
public void onBackPressed() {
if (!mFragments.getSupportFragmentManager().popBackStackImmediate()) {
supportFinishAfterTransition();
}
}
It is normal and expected behavior that OnDestroy() is called after the back button is pressed. This is a standard part of the Android Activity Lifecycle. You can read about the lifecycle here: https://developer.android.com/guide/components/activities/activity-lifecycle.html
I would not recommend overriding the back button behavior as jitesh has suggested unless you have good reason. Users will expect that your app is "closed" (destroyed) once the back button is pressed.
If you want OnDestroy() not being called everytime you tap back button:
#Override
public void onBackPressed() {
// super.onBackPressed(); // remove this line
}
Is there any way to prevent executing code within onResume when returning to an application after the home button has been pressed?
What method is called when the home button is pressed? I could possibly flag something up when home button is pressed?
Thanks
After overriding above method, now you can easily listen HOME Key press in your activity using onKeyDown() method.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_HOME)
{
//The Code Want to Perform.
}
});
Hope this will help
Thanks for the help everyone I managed to solve this by creating a boolean, executeOnResume, which I make false everytime onStop() is called and the app is closed. I then check the state of this boolean in onResume() when the app is opened again to choose whether some code should be executed or not.
onStop()
//-----application stopped
#Override
protected void onStop() {
super.onStop();
//do not execute onResume code when app opened again
executeOnResume = false;
}
onResume()
//-----application resumed
#Override
protected void onResume() {
super.onResume();
//if true
if (executeOnResume) {
//do something
}
else {
//execute onResume true code the next time onResume is called. For example, returning from another activity
}
}
tapping the Home button creates an intent to launch the Home screen and then starts that inten
Correct.
If this is the case, I'd expect the onCreate() method to be run whenever the Home screen is created
Not necessarily. If it is already running, it would be called with onNewIntent().
If someone could just offer some enlightenment into this matter, the basic question is whether onResume() or onCreate() gets called when I tap the Home button
Any time any activity returns to the foreground from a user input standpoint, onResume() is called. Home screens should be no different in this regard.
onCreate() is called when the activity is created. Existing activities are not created, but are merely brought back to the foreground. If what triggered the activity to return to the foreground was a startActivity() call, the activity will be called with onNewIntent() and onResume() (and usually onStart(), for that matter).
Reference : Which method is run when Home button pressed?
Users can leave your app in all kinds of different ways. Pressing HOME is only one of them. An incoming phone call will leave your app, pulling down the list of notifications and pressing one will leave your app, etc. In all of these cases, when the user returns to your app, onResume() will be called. This is standard Android behaviour and tells your app that it is now in the foreground and visible to the user.
Your architecture is flawed if you need to know how the user is returning to your app. You probably need to move some code that you have in onResume() back to onCreate() or onNewIntent().
A game created by cocos2dx. In active scene, when I touch the back button on android, how can i quit it!
can give same example?
Version cocos2d-2.0-x-2.0.4 and cocos2d-x-2.1.4
in our Layer.h:
...
void keyBackClicked();
...
in our Layer.ccp:
Layer::init(){
...
this->setKeypadEnabled(true);
...
}
void Layer::keyBackClicked() {
CCDirector::sharedDirector()->end();
}
Now you are in a position if you click back then you are navigated to the previous screen where you started off your game application right? Then here is the solution: after navigating to the new intent, the previous screen gets in an inactive state in android activity lifecycle you can find that the previous screen goes to a invisible state. Now we can use onPause() method to close the hidden activity. In the same class add this code and your app should be closed when you press back button.
protected void onPause() {
super.onPause();
finish();
}
When you click any button and go to a new intent the application goes to the invisible state and the onPause() method is triggered automatically and it closes the same intent in background.
Override backKeyClicked() method in your layer.
Don't forget to add this->isKeypadEnabled(true) in init method of layer.
In you backKeyClicked method, you can switch it to previous scene or whatever you wanna do.
I want to know how to exit an app when user press the Home Button.
As far as i know that Home Button moves the running app in background and puts Launcher process in front.
I know i can use finish() but i don't know where i should call it because i have no idea which function is going to get a call when user will press the Home Key.
Thanks.
Depending on what you want to do, overriding onUserLeaveHint might be the best bet:
http://developer.android.com/reference/android/app/Activity.html#onUserLeaveHint()
This will let your app know that your app is being exited because the user chose to switch apps (Like by hitting the Home button or selecting a notification). This hint function will not be called if an incoming phone call (or similar) is causing your app to go to the background, as the user didn't initiate that action.
In my case,
I have many activities in application
so if I use 'onUserLeaveHint', 'onStop' or ...
It just catch activity transition.
So I put below code every activities.
And finally catch user's home button action.
first, you have singleton object
public class ActivityContext {
public static Context context = null;
}
and every activities,
#Override
protected void onStop(){ //onStop runs after New one's onResume
super.onStop();
if(ActivityContext.context==context) { //user home button out
AppStartEnd.sendAppEndData(context);
}
}
#Override
protected void onResume(){
super.onResume();
ActivityContext.context = YourActivity.this;
}
I hope this will help you
Let's say I have a Hello World single Activity application. I start this application.
What methods are invoked in each case:
Home button is pressed: ?
Back button is pressed: ?
Phone call is received: ?
What methods are invoked once the user starts the application again via the app icon (assuming the OS hasn't had a "other apps need memory condition"):
Home button was pressed: ?
Back button was pressed: ?
Phone call was received: ?
Thanks all.
Edit: Extra Credit: How can the user invoke onPause without invoking onStop?
both pressing home button and receiving a call don't remove the activity from the task's stack, and will be available when you re-enter the app => onPause() => onStop().
as the activity lifecycle diagram shows, re-entering the app calls => onRestart() => onStart() => onResume()
pressing the back button instead kills the activity => onPause() => onStop() => onDestroy()
re-entering the app in this case calls the classics => onCreate() => onStart() => onResume()
EDIT
from http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
If an activity has lost focus but is
still visible (that is, a new
non-full-sized or transparent activity
has focus on top of your activity), it
is paused. A paused activity is
completely alive (it maintains all
state and member information and
remains attached to the window
manager), but can be killed by the
system in extreme low memory
situations.
There can be several scenarios
Opening the app from the app icon. following methods are called
onCreate()-->onStart()-->onResume()
When user presses the home button
onPause()-->onStop()
When user returns to the app from the Activity Stack
onRestart()-->onStart()--> onResume()
When the app is running and user presses the power button
onPause()-->onStop()
When user unlocks the phone
onRestart()-->onStart()--> onResume()
When user gets an incoming call while you are in the app
onPause()
When user returns to the app after disconnecting the phone call
onResume()
When user presses the back button from the app
onPause()-->onStop()-->onDestroy()
And when the user presses the home button and from the activity stack user swipes the app.onDestroy() method may or may not be called depending upon the OS contains the context of the Activity or not according to memory requirements
Well see, while a sequence of events may occur with your hello world program, the same sequence may not occur in say a video game, because Android will probably Destroy it for taking up too much resources.
The best way I have found to see the lifecycle for my app is to override all the methods (onStart, onRestart,..., including the onSaveInstance and onRestoreInstance) and insert log statements in each one. Like so:
#Override
public void onDestroy() {
// Call the super class
super.onDestroy();
// Log the action
Log.d("Debug", "onDestroy() has been called!");
}
Now I can go to logcat and see what events took place.