I am confused about activity lifecycle usage in the notepad example,notepad example use "edit in place" user model,inserting new record in onCreate method,
saving persistent state in onPause method,and save away the original text in onSaveInstanceState method.
I am a J2EE programer,I can not understand the logic described above. why not make things simple as following:
1.Not inserting new record in onCreate method.
2.When user pressing BACK,it is equal as pressing save button in the editorform,so execute inserting or updating in onPause method if activity.isFinishing() is true.
don't persiste use data if activity.isFinishing() is not true.
3.Not save the original text in onSaveInstanceState method,It is no necessary.If the activity is killed and back,restore user inputing data in the editorForm is adequately.
I think this logic is more traditional and natural.
Maybe I not understand the essence of the activity lifecycle.Please air your's opinion.
Thanks
L.J.W
the lifecycle of an adroid app under various conditions (e.g. switching screens, freezing, stopping etc.) is described in an excellent video tutorial by google. You may also want to refer to the slides of that talk, in particular, slide 16ff may be of great interest for you.
In any case you are right in thinking that understanding the lifecycle of an android app is the key to coding for android.
Related
I am developing an Android application. There is a activity form. The user is going to fill out the form. To fill out the form the user need to go to other forms and after getting back the form is reloading.
I want the form to resume, not to re-create.
may help you also: http://developer.android.com/reference/android/app/Activity.html
#Override
public void onResume(){
// put your code here...
}
This is correct behavior, according to the documentation. You will want to override onSaveInstanceState() to save what the Activity currently looks like, and then properly recreate it in onCreate().
Do this well, and your app will be rock solid. Some folks will generally recommend certain lazy short cuts which are not recommended and will in some cases lead to very unstable applications.
There are two ways you can do this:
Use startActivityForResult() , It will start another activity (means new forms etc) and then you will return back to original activity without any recreation of views and elements. You can do your stuff in onActivityResult()
See How to manage `startActivityForResult` on Android?
Or save your data in onSaveInstanceState() before leaving to activity and on returning back reload data.
see this thread for further help
onSaveInstanceState () and onRestoreInstanceState ()
I have an android requirement where i have created a form like structure have radio buttons, edit texts and so on. When the user make half entries to the form and say moves away from the page either by back button or battery off. When he returns to the form, the same state of half filled form should re appear. Please suggest if android has internal functionality to save the form state and restore when the user revisits. Also, the stored contents should be saved only for particular duration say one hour after which the fresh form should appear. Please help with possible methods applicable for me to start with.
I recommend reading the Android Activity lifecycle. From the webpage:
"In addition, the method onSaveInstanceState(Bundle) is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in onCreate(Bundle) if the activity needs to be re-created. See the Process Lifecycle section for more information on how the lifecycle of a process is tied to the activities it is hosting. Note that it is important to save persistent data in onPause() instead of onSaveInstanceState(Bundle) because the latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation."
At the moment I'm a little bit confused about the lifecycle management in Android. There are at least 4 possibilities to resume retained data after an Activity comes back to the foreground:
Android handling: If there is enough memory, Android stores and resumes the important data (checked radio buttons, text of EditText,-... and so on) after Activity restart, the user has the same state as before as the Activity went into background.
onPause, onResume: Overriding onPause and save the important data to a database or text file and resume it when onResume is executed next time.
onSavedInstance(Bundle), onRestoreInstance(Bundle): I can save the data as key-value-pair into bundles and restore them after onRestoreInstance is executed.
onRetainNonConfigurationInstance(), getLastNonConfigurationInstance(): I handle all my storage issues in one big object and read getLastNonConfigurationInstance() out when onCreate is executed.
Although it is confusing which approach is best, I guess it relies on development experience to know when to use which possibility. If you have some good examples for each I would be glad, but this is not my question. I wonder how to deal with all that when I have different Activities and one Activity will be killed by Android when it pauses in background:
In my case I have a MainActivity and a MessageActivity. The MessageActivity consists of a ViewSwitcher which consists of two states. State one is a radio button choice list. State two is an EditText with two buttons (send and abort). When I monkey test each state, hit the Android home button, and restart the application, the right Activity with the right state and the old data comes into foreground, when I leave the handling to Android. So that works.
But what happens when Android destroys the MessageActivity in background:
If I use the Android way, the data is lost and I guess MainActivity (instead of MessageActivity->state(1 or 2)) will start next time after I relaunch the application (is that correct?). So when I'd like to keep the data of MessageActivity, I have to use one of the other three possibilities.
How to do that neatly, when the application entry point (so the MainActivity) differs from the last active Activity. The problem is that I have to resume a special Activity with a special state of ViewSwitcher. I could start MessageActivity out of MainActivity with startActivity(Intent) in onStart() or onResume() method (because MainActivity is probably the entry point) but then I run into a lot of logical problems in Lifecycle management. Due to this fact I don't think that this is the right way to do that.
But, what's the right and best way to do that?
I guess MainActivity (instead of MessageActivity->state(1 or 2)) will start next time after I relaunch the application (is that correct?)
No, I don't believe this is correct, depending on what your code does in onCreate(). It certainly doesn't need to be correct if you go about things the right way. A simple way to test this is to rotate your screen, which recreates the running activities, unless you have overridden the default configuration change behaviour.
I recommend reading this section in the android docs carefully:
http://developer.android.com/guide/topics/fundamentals/activities.html#SavingActivityState
In particular:
even if you do nothing and do not implement onSaveInstanceState(), some of the activity state is restored by the Activity class's default implementation of onSaveInstanceState(). Specifically, the default implementation calls onSaveInstanceState() for every View in the layout, which allows each view to provide information about itself that should be saved. Almost every widget in the Android framework implements this method as appropriate, such that any visible changes to the UI are automatically saved and restored when your activity is recreated. For example, the EditText widget saves any text entered by the user and the CheckBox widget saves whether it's checked or not. The only work required by you is to provide a unique ID (with the android:id attribute) for each widget you want to save its state. If a widget does not have an ID, then it cannot save its state.
What this means is, that so long as you don't force any UI state in any onCreate() calls, your activity stack and UI state will be restored.
Personally, my preferred approach is to keep as little state as possible in member variables of my activities, saving and restoring it with onSave/RestoreInstanceState(), and relying on the default implementations to save the rest of the UI state (text box contents, etc). Data that should persist between sessions I commit straight to my DB or preferences as soon as it's changed (e.g. in the on-click handler). This means I don't need to worry about the activity lifecycle for that. As much as possible, my UI just presents a view of the data in my DB (using CursorAdapter etc.).
Edit:
Regarding restoration of the whole activity stack:
When the user leaves a task by pressing the HOME key, ... The system retains the state of every activity in the task. If the user later resumes the task by selecting the launcher icon that began the task, the task comes to the foreground and resumes the activity at the top of the stack.
(See http://developer.android.com/guide/topics/fundamentals/tasks-and-back-stack.html)
It's not my attempt for a best answer, but it's too long to get in the comments section.
First I will suggest not to rely on the "Android way" - this will result in inconsistent application behavior depending on the free memory of the device - bad practice.
My suggestion is to save your state-dependent data in key-value pairs in SharedPreferences, every time you go into onPause() in your MessageActivity. Store a flag in SharedPreferences, which indicates which was the Activity that was last opened (if you only have two Activities you can easily go 0/1 or true/false flags).
When you re-launch your application, it's normal to start the Activity marked in your AndroidManifest.xml as "entry point". So naturally you'll check the flag in onResume() in your MainActivity and start the other Activity if needed. In MessageActivity's onResume() check the values in SharedPreferences and fill in what's necessary...
If your application is "resumed" to the last Activity in the ActivityStack this will call onResume() in the last Activity in the ActivityStack.
The way I have handled an issue like this in the past, is to have a service running in the background, which handles the flow of information from different activities via either Intents and listeners (preferable, since they are the most easily decoupled solution), or if you are extremely careful, and the only viable solution for some reason is to store the data through direct property access or method calls, you can use static properties/methods on the service class as well. However, I would strongly recommend using the Intent/listener method as it is generally more flexible, thread safe, and decoupled. Additionally, it is wise to make sure that not much is happening at any point in time (in other words, only use this service for Intent handling) when it's not needed, otherwise the Service will tend to hog CPU time as well as RAM, when it's not really needed.
Some resources to look at when it comes to this approach would be IntentService and its related classes, including the superclass, Service. IntentService, however, it is worth noting handles a few more things about async Intent processing, etc that Service does not automatically come with.Hope this helps you!
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name=username.getText().toString();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
editor.putString("username", name);
if(name.equals("xxx")) {
Intent intent=new Intent(currentactivity.this,nextactivity.class);
intent.putExtras(bundle);
startActivityForResult(intent,0);
}
}
});
I have finished the Layout exercise and wondering why they include the call to populateFields() in both onCreate and onResume.
According to Activity Lifecycle "onResume" will always be performed before the Activity is shown so why not just there?
I have real production code that populates fields and is only called in onResume and it works just fine.
I thought one reason would be that maybe onResume is called after the activity is shown, but a bit of googling digs this (mostly unrelated) thread:
http://groups.google.com/group/android-developers/browse_thread/thread/ddea4830bedf8c6c?pli=1
Quote: onResume() is thus the last thing that happens before the UI is shown
This is what Dianne Hackborn says so i guess we can trust her :)
Actually I have seen apps (in my app and also others), where fields were only populated in onCreate(), but not in onResume().
Lets call that app 'A'.
The effect was that when the user pressed the home button, went to a different app, and then returned to 'A', the screen stayed black, as 'A' was still in memory and thus the system did not bother to call onCreate(), but directly went into onResume().
So basically I'd say (and this seconds what #Torp wrote) populate the UI in onResume() and be done.
But then, this answer is slightly off-topic as it does not answer your "why" question.
You don't populate in onResume because it will be called every time the activity is shown.
You generally want to create as few objects as possible, so you create them once and for all in onCreate, and then you can always check that they are still updated in onResume.
I'm developing an Activity that does some of its own state management. I'm trying to differentiate the following onResume cases:
New launch
task switch (home button long-click)
resume after other activity in the same application
wake-up after sleep
orientation change
Is there something in the Activity's intent, or elsewhere, that can help me differentiate these?
For the curious and some context... I'd like to preserve my internal history stack on 4 & 5. On cases 2 & 3, I would preserve the same current page, but erase the history (allow the normal back button functionality to take over at that point). Case 1 would initialize to the activity's internal start page (and can be detected easily enough with some help from onCreate).
Is there something in the Activity's intent, or elsewhere, that can help me differentiate these?
Item #4 has nothing to do with onResume(), AFAIK.
Item #5 would be better handled via android:configChanges and onConfigurationChange() though you could "detect" it by returning something from onRetainNonConfigurationInstance() and seeing if it is there in onResume() via getLastNonConfigurationInstance().
The others aren't just three cases, but probably twice that, once you start taking into account things like "being kicked out of memory to free up RAM" as a possibility.
Off the cuff, it feels like you made some unfortunate architectural decisions ("internal history stack...erase the history...allow the normal back button functionality to take over at that point"). Android is designed around lots of cheap activities, and you appear to be violating that precept. You are welcome to do so, but bear in mind that Android support for your chosen pattern may be limited.