The books I have are abysmal at explaining how to work with the lifecycle, there's a lot I'm missing that I'm hoping somebody can fill in.
My app structure is that when it's first started, it starts an activity full of legalbabble that the user has to accept. When he says 'ok', I start my main activity and then I call finish like this:
public void onClick(View view) { //as a result of "I accept"
Intent mainIntent = new Intent(mParent, EtMain.class);
startActivity(mainIntent); // Start the main program
finish();
}
Then in EtMain in the onCreate method, I've got some tabs and I instantiate some classes:
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
SetupTabs.setMyTabs(mTabHost, this);
mComData = new ComFields(this); // Create the objects
mDepWx = new WxFields(this, DepArr.Departure);
mArrWx = new WxFields(this, DepArr.Arrival);
mDepVs = new DepFields(this);
mArrVs = new ArrFields(this);
mTabHost.setOnTabChangedListener(new OnTabChangeListener(){
}
Questions:
The 'finish' in the first fragment should terminate the legalbabble activity so it'll never be restarted, right? And the EtMain one will remain forever (until killed externally), even if my app gets pushed to the background, right?
The way it is now, when EtMain gets pushed and later brought to the foreground (by tapping on the icon), it goes through the legalbabble screen as though it's a complete start - that's what I'd like to prevent - going thru the legalbabble screen again.
It would seem that I'd want to override onRestart in the second code fragment and put something in there to restart the app, right? That's the part I'm unclear about.
My question then is what needs to be done in onRestart. Do I have to recreate all the tabs and data in the tabs and all my object instantiations? Or is the memory state of the app saved someplace and then is restored back to the state that it was in before something else was brought to the foreground in which case not much needs to be done because all the objects and listeners will still be there?
Yes after the first activity has ended you shouldn't have to view that activity again. You could also write to the shared preferences that the user has previously seen legal info.
If you're UI object creation is in the onCreate method, this should only be called once. Pausing or resuming will not call the onCreate method again.
Unless you explicitly remove your objects and tabChangedListeners in the onPause method, you should not have to touch them in the onRestart method.
Correct, the state of the app is saved automatically. You shouldn't have to touch the onRestart method.
Hope this helps!
I think the problem is that the launch activity in your manifest is the legalbabble activity, so when you click on the icon, the system launches another one. A better architecture would be to launch the legalbabble activity it from your EtMain activity in the onCreate method of the latter, using startActivityForResult. From the docs:
As a special case, if you call startActivityForResult() with a requestCode >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your activity, then your window will not be displayed until a result is returned back from the started activity.
When you get the result in onActivityResult, you can call finish() if the legal stuff was declined; otherwise everything will proceed normally.
This avoids the problem that the launch activity defined in your manifest finishes when the legal stuff is accepted.
EtMain will not remain forever, if the user backs out (by pressing the BACK key) the Activity will be finished (onPause, then onStop, then onDestroy will be called).
In general you can ignore onRestore until you are doing something complicated.
Once the user has exited your application and re-enters (or presses the icon on the Homescreen), onCreate (followed by onStart and onResume) will be called for your first activity, so you do not need any logic in onRestart, your code in onCreate will do the setting up for you as it did the first time. Because of this your legal babble will appear again when the user starts the app after exiting unless you store a preference (in SharedPreferences or a database or file) to indicate you have already displayed it - in which case finish it straight away and start the main activity.
onRestart is only called when the application goes from the stopped state (onStop has been called but not onDestroy) to the started state (onStart is called but onResume has not yet).
For saving data - some components save their state automatically (e.g. EditTexts remember the text in them, TabHosts remember the currently selected tab etc). Some components will not. If you wish to save extra data then make use of onSaveInstanceState and onRestoreInstanceState. You should only use these methods to restore the state of your application or temporary data, not important things, e.g. the id of the resource what the user was looking at, what zoom level they were at etc. For things like contacts or actual data you should commit these changes to a database, SharedPreferences or other permanent storage (e.g. file) when onPause is called.
I recommend taking a look at the Android Activity lifecycle if you are confused. Or ask more questions!
Related
This is harder than it sounds, which is why I'm asking for solutions.
Basically I only want the disclaimer Toast shown once per run of the app.
The app is in two parts, all are Activities.
It's shown when it starts in the first part, but you can hit a menu button
taking you to the second part of the app, which has another menu button
to take you back to the first.
The problem is that whatever initial settings you try to make in the first
part, when it starts up, are run again when returning from the second
part of the app, so it'll show again.
My last idea was that in the first part's onDestroy(), when the app exits, but is not the case in this situation, you set a boolean in settings,
to reset that the disclaimer can be shown, but apparently, onDestroy() is called on the first part before it goes to the second part.
Or, if you can get it to not show the first run, but behave properly
every time after that, that would be okay.
And there doesn't seem to be any method to be called when the app truly
is "killed", if there was that would be the way to do it, you could reset it there. Or if there was a method that was only called when the app first started..
Thanks!
You just need a boolean flag. Say we call it disclaimerShown. In onCreate() of Activity A, we check both the Intent Bundle and the savedInstanceState Bundle for this flag.
You can add the boolean to a Bundle when launching the Intent to start Activity A from Activity B.
If the user is in Activity B and presses the Back button to return to Activity A, you can override onBackPressed() in Activity B and include your flag there as well (though you'll have to catch this flag on onActivityResult() in Activity A).
If system initiated process death occurs in Activity A, the system will call onSaveInstanceState(Bundle bundle). So you add your flag to this bundle as well.
And if system initiated process death occurs in Activity B, you have nothing to worry.
And that handles all possible cases.
An elegant solution for this problem would be the ProcessLifecycleOwner.
This class provides callbacks to the lifecycle of your whole app (not individual activities) and you could use the Lifecycle.Event.ON_CREATE callback to show your toast once. Look at this stackoverflow question for a usage example of the ProcessLifecycleOwner.
It turns out that I already had an Activity that started before
my "Activity A", and I moved my disclaimer Toast there
and it works fine. You can't beat that simplicity lol.
Thanks for your answers!
Just looking at this documentation about Activity Lifecycle
https://developer.android.com/reference/android/app/Activity.html
it seems to me the onResume callback is not really a real resume. Because it will run if
a. Activity is just created, even if it was not paused.
b. Activity was paused and then it's resumed.
I am sending a user to another activity to do stuff, and depending on what the user did on those other activities, when they return, I need to decide whether to reload the app manifest. However, I don't even wanna check if the app was not paused at all! (ie. the user just opened the activity)
Is there a better way to track if the user is really resuming other than creating a variable in onPause that I will check when the user returns?
Declare a boolean flag in your activity:
boolean hasBeenPaused = false;
Now in your onPause(), set this to true:
public void onPause(){
hasBeenPaused = true;
}
Since your onResume gets called whether or not the app was previously paused, you can now check the boolean and know if it's a fresh start onResume or post pause onResume
public void onResume(){
if(hasBeenPaused){
//onPause was called
//May be because of home button press, recents opened, another activity opened or a call etc...
}else{
//this is a call just after the activity was created
}
}
If you want to persist, you can even save this variable inside onSaveInstanceState and get the saved state in your onCreate
If you are absolutely against setting the variable in onPause and want to ensure that a change was made before reloading the data then set a variable in your API calls that triggers a reload when the user comes back to the activity. Depending on your application structure you could even do the reload before hitting onResume in the activity.
Also be aware that onResume will be called if you're in a fragment and provide a popup (such as an activity indicator).
I have two activities; let's say A and B. In activity A there is a broadcast receiver registered that listens for a particular event which will finish activity A. I am registering the broadcast receiver in onCreate(), and destroying it in onDestroy() of activity A.
For simplicity, there is one button in activity B named "Destroy Activity A". When a user clicks on button, activity A should be destroyed.
Normally all of this is running smoothly without any issues,but the problem occurs in following scenarios:
1) Suppose I am in activity B and i press the Home key to move the application to the background then if i use other resource-heavy applications, Android system will kill my application to free memory. Then If I open my application from recent tasks, activity B will be resumed, and it's onCreate(), onResume() etc method will be called. Now I press button to destroy activity A, but activity A has already been destroyed, so activity A's onCreate(), onResume() etc methods will not be called until and unless i go to activity A by pressing the back button. Thus broadcast receiver is not registered to listen for the event.
2) The same problem will arise when user has selected "Don't keep activities" from Developer options in the device's settings.
I have been looking to solve this issue for a long time, but i am unable to find a proper answer. What is the best way to handle this scenario? Is this an Android bug? There should be some solution for this issue.
Please help me.
If your Activity A has destroyed by Android OS itself then there are
no way to track.
Some people has suggested to track that Activity A by listning event in onDestroy method BUT if your Activity killed by system OS then note here it wont call those method .
This cannot be fixed while keeping your current broadcast logic.
Killing activities from the backstack, imo, is not a correct approach. You should strongly consider changing the logic of your navigation.
But if your project is big and time is a problem, and refactoring is out of the question, A.J. 's approach works, but you mentioned that you have lots of activities that needs to be killed, his solution becomes very tricky to implement.
What I suggest is the following. This might not be the best idea, but I cannot think of another. So maybe that could help.
You should have the following:
A Base Activity for all your activities.
A ArrayList<String> activitiesToKill object at the application level. (If you did not extend Application you can have it as static variable
First we have to make sure that the activitiesToKill is not lost when the OS kills the app in low memory. In the BaseActivity we save the list during onSaveInstanceState and restore it in the onRestoreInstanceState
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("activitiesToKill", activitiesToKill);
}
private void onRestoreInstanceState(Bundle state) {
if (state != null) {
activitiesToKill = (ArrayList<String>) state.getSerializable("activitiesToKill");
super.onRestoreInstanceState(state);
}
}
The idea here is to save which activities should be killed in the list, by using their name.
The logic is as follow:
Let's say you have Activities A, B, C, D and E
From Activity E, you press the button and you want to kill B and D
When you press the Button in E, you add the names of B and D to the activitiesToKill object.
activitiesToKill.add(B.class.getSimpleName()
activitiesToKill.add(D.class.getSimpleName()
In the onCreate method of the BaseActivity, we have to check if the
if(savedInstanceState != null)
{
//The activity is being restored. We check if the it is in the lest to Kill and we finish it
if(activitiesToKill.contains(this.getClass().getSimpleName()))
{
activitiesToKill.remove(this.getClass().getSimpleName())
finish();
}
}
Make sure to remove the name of the activity if it is killed through the broadcast.
So basically this is what happens in every scenario.
If the app is running normally, and you click the button, the broadcast gets sent and B and D will get killed. Make sure to remove B and D from the activitiesToKill
If the app was killed and restored, you press the button, the broadcast will have no effect, but you have added B and D to the activitiesToKill object. So when you click back, the activity is created and the savedInstanceState is not null, the activity is finished.
This approach consider that activity E knows which activities it has to kill.
In case you DON'T know which activities to kill from E, you have to modify this logic slightly:
Instead of using an ArrayList use a HashMap<String, bool>
When Activity B is created, it will register it self to the hashmap:
activitiesToKill.put(this.class.getSimpleName(), false)
Then from Activity E, all you have to do is set all the entries to true
Then in the on create of the base activity you have to check if this activity is registered in the activitiesToKill (the hashmap contains the key) AND the boolean is true you kill it (don't forget to return it to false, or remove the key)
This ensure that each activity register itself to the HashMap and Activity E doesn't have top know all the activities to kill. And don't forget to remove them in case the broadcast kills them.
This approach also ensure that the activity is not killed when opened normally from an intent because in that case onSaveInstanceState would be null in the onCreate, so nothing will happen.
More advanced checks can be accomplished in case you have groups of activities that needs to be terminated through different conditions (not only a button click) so you can have a HashMap of a HashMap to divide them in categories.
Also note, that you can use getName instead of getSimpleName if you have multiple activities with same name but different bundles.
I hope my explanation is clear enough as I wrote it from my head, let me know if any area is not clear.
Best of luck
One of the main rules with Activities is you can't rely on any activity being alive except the foreground activity. The thing you're trying to do with broadcasts has nothing to do with back stack -- back stack doesn't guarantee all activities are alive at all times, but it will make sure they're recreated when it's time to go foreground.
In your example (if my understanding of what you're aiming to do) you need to navigate to something underneath A -- say, Activity Z, and the stack looks like this: Z-A-[B]. There's normal course of events where you hit back and it takes you to A, then after another hit -- to Z but in a certain case (say pressing a button) you want to move back to Z bypassing A -- this is a classic case to use FLAG_ACTIVITY_CLEAR_TOP and launch Z explicitly:
Intent intent = new Intent(this, ActivityZ.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
This will finish both B and A, and deliver the intent to Z. You will, probably also need the FLAG_ACTIVITY_SINGLE_TOP flag, pay close attention to the description of FLAG_ACTIVITY_CLEAR_TOP, there's some trickery you should consider.
I don't know if it's possible to handle this on a "proper" way.
What it comes to my mind, is to flag the A activity in some way. You can't use startActivityForResult() because you will receive the result before onResume() is called i.e. UI was already inflated.
If you using an Otto, you could try with a sticky event. Otherwise you will need a singleton to handle the flag or save it to shared preferences.
You will have to check that flag on your onCreate() method before calling setContentView(), if the flag is true just finish the activity.
With the information you have given, how about you register the broadcast in onCreate of Activity B after checking if its registered already or not. If onDestroy of Activity A has been called in either of the scenarios you have mentioned, then the deregister of the Broadcast would have been called. So in that case, you can register your Broadcast in onCreate of Activity B, so that you can listen to it, even if you have only the Activity B in your backstack.
Have you considered using Sticky Broadcast?
Also you can register your receiver on application level (in manifest) and listen to this event regardless of Activity A state.
But, like already said Youssef, killing activities from the backstack is not a correct approach. You should strongly consider changing the logic of your navigation.
Many solutions came to my mind but as you have not provided much information about your app, so I think this should work in general.
Instead of firing a broadcast to kill Activity A, just execute the following code when the "Kill Activity A" button is pressed in Activity B.
Intent intent = new Intent(getApplicationContext(),
ActivityA.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
intent.putExtra("EXIT", true);
startActivity(intent);
Add the following code in activity A
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent.getBooleanExtra("EXIT", false)) {
finish();
}
}
protected void onCreate(Bundle savedInstanceState) {
//Ideally, there should not be anything before this
super.onCreate(savedInstanceState);
if(getIntent().getBooleanExtra("EXIT", false)){
finish();
return;
}
In the manifest set "singleTop" launch mode for activity A.
<activity
android:name=".ActivityA"
...
android:launchMode="singleTop" />
This will have the following consequences:
If Activity A is already running it will brought to the front of the activity stack and finished, thus removing it from the stack.
If Activity A has been destroyed but still present in the activity stack (to be launched when back button is pressed), it will be started, brought to front and finished, thus removing it from the activity stack.
If Activity A has already has already been destroyed and not present in the activity stack, and you still press the "Remove Activity A" button, it will be started, brought to front and finished.
Generally, you should not see any flicker.
Based on this idea, you may build a better performing solution for your particular app. For example, you may use the FLAG_ACTIVITY_CLEAR_TOP and finish the Activity A in onBackPressed() of Activity B.
Let's say we have a default, empty activity with default behaviour, launched with default intent flags. User presses back button on the device. The activity disappear... but how, actually?
Is pressing back button behaving the same way like finish()?
Is the activity immedietely destroyed (onDestroy is called)?
Is the activity guaranteed to be destroyed, but not immedietely?
Is there any chance the activity won't be destroyed and this instance will be reused when this activity is launched in the future? (so only onPause and onStop -> onStart and onResume are called?)
I'm looking for a reliable answer, so please do not answer if you are not absolutely sure what happens here.
http://developer.android.com/training/basics/activity-lifecycle/recreating.html
This is a subchapter from the official Android documentation that addresses your question. It is a subchapter of the topic Managing the Activity Lifecycle, which can be read here:
http://developer.android.com/training/basics/activity-lifecycle/index.html
It is definitely worth reading the whole chapter to get to know the details about Androids Activity behaviour. But the subchapter ( first link ) is the relevant part to this question.
you use should look into this try this
and please tell specific what you wish to do with back button for your default activities ......
When you press back, (if not intercepted by anything like the keyboard, fragment, activity, etc) the OS (via ActivityManager probably) will try to show the user the previous activity in your current task (again, ignoring fragments' back stack).
If there is no such activity, the task will be terminated and you'll go to the previous task - the home screen most of the times or some other application that might have launched your app.
You'll get onDestroy called soon (it depends on how long it takes to start the next activity but on a good phone it should be under 100-200ms).
Your activity instance won't be reused after onFinish. This happens before the activity is destroyed so if you need another activity of the same type, the OS will create another instance.
When the user presses the BACK key, the current activity is popped from the top of the stack (the activity is guaranteed to be destroyed, but not immediately, may be when the system resources are low) and the previous activity resumes (the previous state of its UI is restored).
Which actions does the back button/back key on Android trigger?
Definitly onDestroy() is called .....There are a few scenarios in which your activity is destroyed due to normal app behavior, such as when the user presses the Back button or your activity signals its own destruction by calling finish().
I am making a activity using Tab-Host.
I have two tabs. When I start the tab-Host activity, the tab-Host opens the activity and the life-cycle of the activity is calling but when I changed the tab and again open that previous tab the activity is not getting its callback methods like resume.
I don't think there is any specific reason it should restart. For changing configuration (like rotating the device or sliding out a keyboard) there is a specific trigger because the app needs to deal with the change. But any other process should go according to the Activitvy lifeCycle
When your app goes to the background (looses focus) for any reason you get onPause() called, and when it goes back, your onResume() will be called. This is the same for when you go home and then back to your app, or when you switch activities like that. No new intent or something like that, just going back to the activity.
You should put your code that needs to run in the onResume().
Do what you need to do in the activity in onResume() instead. That will get called everytime, not just the first time it is created.
http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
When you switch from one tab to the other and back, the first tab only gets its onResume method called since it has already had its onCreate called the first time.
You can run the code you like in your onResume method if you want anything specific to happen when it gets focus again.