I am making an application in which i want to let the control go to some activity and then to come back. When I have searched about that problem, I came to know that this problem could be solved by using OnPause() and OnResume(), but I don't know how to use them.
This is the code where I am transferring the control to some other activity. Please tell me how to use OnPause() and OnResume() in this regard.Thanks in advance.
Intent intent = new Intent(MCQ.this,ConfigActivity.class);
int ClassIndex = 2;
intent.putExtra("ClassIndex", ClassIndex);
startActivity(intent);
You are not making too much sense. When you call startActivity(), Android will put your current Activity to the background, and start (or bring to foreground) the new Activity specified in your Intent.
onPause() called when your Activity disappears from the screen, eg. the system either puts it in the background, or terminates it.
onResume() is called when your Activity becomes visible on the screen, eg. either after onCreate() if Android created a new instance of your Activity, or when the system brings your Activity back from the background.
There is no explicit passing of control between Activities. If it is on the top of the activity stack (visible on the device screen), than you can interact with it.
http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
onPause() and onResume() are called by android.
Your job is to implement these methods. onPause and onStop are called at your launching activity by Android, and onCreate, onStart and onResume at the Activity your starting. If you want to go back, you usually just press the back button at your device.
You might want to take a look at the Android devGuide and especially at the Activity lifecycle.
I think you may be confused as to what onPause() and onResume() are used for.
onResume() is called when the Activity is about to show it's view to the user. You can use your intent in this method so the main Activity would instantly go to the ClassIndex activity. However, when you leave the ClassIndex activity, onResume() will be called again which will send you back to ClassIndex.
onPause() is called when the Activity is leaving. Whether this is for locking the screen or moving to another Activity. In this case, when you call startActivity in the main Activity, Android will call onPause() in the main activity before entering the new one.
What you may want in this case is to use startActivityForResult() and use it to determine if you're coming back from your ClassIndex activity or not. If not, then start it. If so, then move on to the main activity.
A better solution may-or-may-not be to start the app in ClassIndex and move to your main activity when the user is done with it. This would be the case if you want to move to ClassIndex every time the user enters the app.
Related
Whenever a new Activity is created onCreate is called. Followed by onStart. And onStart is called again when activity is back on to the screen. I know this fundamentals. But, what is the actual difference between when you launch the activity.
I mean to say, when you click on some object on current activity, you start a new activity by startActivity() method with an intent of new activity. Now onCreate() will be called of the second activity and then the onStart(). When will be the activity visible to the user? After onCreate or after onStart? If it is visible after onCreate and before onStart, and I do some of the operations in onStart(), then it will reduce the lag between the user clicking on an object and the screen popping up on screen.
If I move some of the data bindings to onStart will it interfere with the default Activity transitions on lollipop and above (I am not sure about this)?
Is it a good idea to move some of the code to onStart to reduce a lag between click and new activity shown on user's screen? If yes, what kind of code can be safely moved to onStart? Like data bindings, database queries, etc. ?
Any guidance will be much appreciated.
If I have a method called onStop and it calls super.onStop();. When does this method run?
In my main activity, I start another activity as follows: startActivity(new Intent(this, MyNewActivity.class));. Does this automatically stop my main activity and call onStop?
Also, what kind of things should I do in the onStop method of my main activity. So far all I have done is unregister listeners to free up space but other than that is there anything else I should do?
Thank you, any help is greatly appreciated.
When does this method run?
This method calls when your Activity is no longer visible to the user
Does this automatically stop my main activity and call onStop
Yes when you start another Activity first onPause() function get called and then onStop().
what kind of things should I do in the onStop method of my main activity
It depends on your implemenetation and your needs but persisting data recommended to implement on onPause() callback function
In my main activity, I start another activity as follows: startActivity(new Intent(this, MyNewActivity.class)); Does this automatically stop my main activity and call onStop?
You can know yourself what happens when you call new activity takes focus just put a simple log statement and check yourself.
http://developer.android.com/guide/components/tasks-and-back-stack.html
Quoting from the docs
When the current activity starts another, the new activity is pushed on the top of the stack and takes focus.
The previous activity remains in the stack, but is stopped. When an activity stops, the system retains the current state of its user interface. When the user presses the Back button, the current activity is popped from the top of the stack (the activity is destroyed) and the previous activity resumes (the previous state of its UI is restored).
onStop()
Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed.
Followed by either onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away.
Check the topic saving activity state
http://developer.android.com/guide/components/tasks-and-back-stack.html#ActivityState
Note: When the system stops one of your activities (such as when a new activity starts or the task moves to the background), the system might destroy that activity completely if it needs to recover system memory. When this happens, information about the activity state is lost. I believe this happens on priority basis.
If you need to store persistent data do it in onPause
For more info check the activity lifecycle
http://developer.android.com/reference/android/app/Activity.html
I have Activity A and I am calling Activity B from Activity A using setResultForActivity.
Now in Activity B when I press Done button I am firing finish() and it returns to
Activity A and it return down to onActivityResult. Now the issue is after when I fired finish() in Activity B , Activity A's onCreate doesn't get called and thats why
some of the custom listeners in my ListView isn't working , it seems that they are not bind.
so the whole activity respond pretty weirdly , can anyone has solution to this ?
Why a fourth answer? Because in my view, the others aren't fully correct.
Truth is, Activity A could have been destroyed in the meantime, or not. This depends on whether Android needs memory or not. So it is possible that Activity A´s onCreate() is called (along with the other lifecycle callbacks), or not. In the latter case, onActivityResult() is called before onResume().
While for configuration changes, the most efficient way to preserve the Activity's state is via nonConfigurationState, if you want to prepare for a restart of your Activity after it has been destroyed, you can use the InstanceState mechanism, because while Android destroys your Activity A, it will keep its intent and saved instance state to re-crearte it.
This stresses the absolute necessity to place initialization exactly in the callback where it belongs.
To test whether your Activity logic works regardless of whether Android destroyed it or not, you can use the DevTools setting "Development Settings" -> "Immediately destroy activities". The DevTools app is available on AVDs and can also be downloaded from Google Play.
Just place your onCreate() stuff in onResume() of Activity A except setContentView().
Just have a read on Android Activity Lifecycle : http://developer.android.com/training/basics/activity-lifecycle/stopping.html. onCreate() is only called when the activity is first created. You can do your list thing in the onResume() method.
Activity A's onCreate won't get called because the activity has not been destroyed. When an Activity regains focus from another activity, it's onStart and onResume get called, so I would put your bound listeners in those. They will also be called when onCreate is normally called.
After your child activity is finished() it return to execute onActivityResult which is in your case in Activity A. The onCreate method is not supposed and does not get called when killing of you sub-activity, a.k.a Activity B.
Please post some source code for us to work on and I will improve my answer! :)
The Activity Lifecycle is giving me headaches.
The documentation at http://developer.android.com/reference/android/app/Activity.html is so darn ambiguous when it describes the concept of visibility, that I can't figure out when onStop() is called vs onPause().
Compare the following two statements from the documentation:
(taken from right beneath the lifecycle diagram)
The onStart() and onStop() methods can be called multiple times, as
the activity becomes visible and hidden to the user.
vs
(further down in the blue table with the "killable" columns)
onPause() Called when the system is about to start resuming a previous activity.
What I'd understand from the first quote, is that onStop() is called on activity A when A is "hidden". "Hidden" I'd guess is referring to when another activity B has been resumed and is completely covering actvity A.
But the second quote then states that onPause() is called when another activity is about to start resuming. Wouldn't that completely hide activity A as well? Both cases seem to imply that that activity A becomes "hidden", no? According to my likely faulty interpretation, onPause() and onStop() are called in identical situations.
The documentation also seems to differ between being hidden (onStop() gets called) and being partial visibility (onPause() gets called). But when is an activity still partially visible? Do they mean literally? Or can an activity still be deemed "partially visible" when it has started up a new activity (activity calls startActivityForResult and starts a date picker activity) that covers the entire screen? Surely the activity is not going get onStop invoked? Its supposed to receive a result any moment!
So I'm trying to figure out what I'm not getting.
I understand that a call to onPause is guaranteed. That would be when activity A loses focus (device enters sleep mode, screenlock, etc), a different activity B takes the foreground (where activity B may or may not have been initiated by activity A).
But at which point is the onStop() invoked on activity A?
Is it matter of how many activities have been piled ontop of activity A on the activity stack? Are there two different definitions of "visiblity" at play?
Sorry about the wall of text, but I'm really frustrated :S
So the question stands: Precisely in which situations is an activity deemed "hidden" such that onStop() is called on it?
EDIT:
I inserted Toast notifications in each onX method, and discovered some additional weirdness:
Pressing the Home button will always call onStop(). But starting up the application won't call onRestart(). Instead it calls onCreate(). This seems strange to me, but ok...
When the "USB Mass Storage" activity is started on top of the main activity, onStop() is called. And when exiting the usb storage activity, returning to the main activity, onRestart() is called, instead of onCreate().
When the device goes into Sleep mode and is waken up, the activity only goes through the onPause() and onResume() cycle.
The last point was expected (although I can't get it to fit in the lifecycle diagram). But whats up with 1. and 2. ?
In the first point, I was expecting a call to onRestart() when starting the activity again. Why did it deallocate the activity and call onCreate() instead?
And take a look at point nr 2:
According to the documentation: when "another activity comes in front of the activity", onPaused() should be called. Isn't that what happened when the USB Storage activity came up? It didn't call onPause(), it went through the onStop() - OnRestart() cycle! Obviously, the documentation doesn't consider that a case where "another activity comes in front of the activity". So what really happened?
Ok, I think I've got this now.
1.
The key to the first point was this link:
http://code.google.com/p/android/issues/detail?id=2373
Its a bug. Theres some code in the link that has completely solved the problem with new root activity instances being created, instead of just restarting the last active activity (before the home button was pressed).
I put the code at the top of the onCreate method, just below the super.onCreate call:
if (!isTaskRoot()) {
final Intent intent = getIntent();
final String intentAction = intent.getAction();
if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) &&
intentAction != null && intentAction.equals(Intent.ACTION_MAIN)) {
finish(); return;
}
}
Note that I added the return statement after finish so the rest of the onCreate method doesn't run in the case that the bug is detected.
2.& 3.
The key to the second and third points was these two links:
http://answers.oreilly.com/topic/2692-android-programming-understanding-the-activity-life-cycle/
How to make Activity, not covering full screen
It turns out that "visibility" really is literally! So when the documentation says "another activity comes in front of the activity", the activity behind the bumped activity is still partially visible. This means that the Android Activity manager must check whether the bumped Activity is a full-screen activity or not: If it is, onStop() is called on the previous activity. If not, then onPaused() is called on the previous activity instead.
This trivially explains why the USB Storage manager caused the onStop() to be called.
This also means that when device goes into sleep mode, the Activity Manager considers it a non-fullscreen activity, even though technically the main activity is completely hidden behind it.
(See the second link on how to make non-fullscreen activities )
Interestingly, the pull-down window (with the notifications) doesn't call onPause() (nor does it call onStop()), even though it would have made sense as a non-fullscreen activity. This must be some kind of exception that I'll be investigating on my own.
This also means that the onStop()-onRestart() cycle is probably more common than the onPause()-onResume() cycle (although both must still be accounted for), since activities probably more often than not are full-screen activities (personally, I thought the documentation indicated the opposite: that onPause-onResume was more commmon, but maybe thats just me).
Additionally, this must mean that when the main activity starts a new fullscreen activity for a result, the main activity will be first stopped and later restarted when the result-retrieveing activity is done.
So the only question now is how to best deal with a paused activity (meaning, it is covered by a non-fullscreen activity) that gets deallocated (although this case would be rare). What challenges may there be?
But thats outside the scope of this question.
Finally tracked this down: you can detect the status bar pulldown using onWindowFocusChanged()
how to use OnWindowFocusChanged method
I have an Android activity we'll call A which has a button and another activity B. When the user clicks the button in Activity A, I'd like to finish A (let both onStop and onDestroy finish running) and then start up the instance of B. When I put a finish() and startActivity() call in the button click listener, the instance of B starts up before the old instance of A finishes. Can someone help me figure out a way to do what I'm looking for?
What you are looking for is not possible and actually is against Android's activity lifecycle implementation.
Correction
It is possible with android:noHistory="true" tag in your manifest, but for what you are trying to do it seems wrong (read the EDIT)... Messing with the activity stack makes a non intuitive application!
Android OS doesn't let you control when activities will be removed from memory (or killed), and therefore all these fancy "Task killers" are so popular (DONT use them, they only make things worse).
When your activity's onStop() is being called, the activity stops completely, and it just hangs in your memory, but that's fine...
If you want to reset the state of activity A, or close the app when exiting activity B, just create a set of rules in both onResume() and onStop(), you can do everything you wish by creating a set of rules in those functions.
for example: have a boolean in activity A that turns true just before calling activity B,call finish() on your activity A's if this boolean is true
I suggest that you take a look at Android's Activity lifecycle diagram, and make sure that everything you do follows the best practice.
EDIT
I saw your comment, it seems like you are trying to create things that are already in your memory, don't recreate them, it's a waste of CPU time, memory, and battery.
Instead, create a static class with a singleton that will hold all your shared data !
I believe you're looking for
onPause()
which is what gets called when the activity is sent to the background. You can do whatever cleanup you want in there. onStop should only be called when a user is exiting out of your program (or launching another one)
onPause is a better place to do this cleanup. See the Saving Persistent State section of the Activity doc.
When an activity's onPause() method is called, it should commit to the backing content provider or file any changes the user has made. This ensures that those changes will be seen by any other activity that is about to run. You will probably want to commit your data even more aggressively at key times during your activity's lifecycle: for example before starting a new activity, before finishing your own activity, when the user switches between input fields, etc.
While I'm not definite that your cleanup is for user changes, the bold sentence above implies that onPause will complete before the next Activity is created. Of course that probably implies that you'll have to move some setup to onResume...
Alternatively, you could move all your cleanup code to a method, let's just call it cleanup and then just call it before you start activity B. You'll have to put in appropriate guards for your onDestroy cleanup too of course.
override finish() method.
implement cleanUp() method.
create boolean isClean=false in the activity
in cleanUp() write your clean up code.
call cleanUp() in your finish()
check for isCleaned in finish() or in cleanUp() if its true then ignore the clean
now before you start B , call cleanUp() and set isCleand=true
after you call B , call finish()
Start activity A
from inside A startService(c) and finsh A
from inside the service , start Activity B