Understanding Android activity onCreate method
When you developing in Android, you are not start from scratch, you are in a framework, it's like developing a plugin, provides some implementations for existing interfaces in the framework, and the framework will call your code at appropriate time.
In most cases you start from override an inherited method, this post will introduces the onCreate method.
As the name indicated, this method is invoked by Android Activity Manager when the activity is first created.
Here is a typical example of onCreate method in an activity class
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.hello_layout); }
Bundle
As you can see the onCreate method has a Bundle parameter, it's just an object that contains a small amount of data usually about the state of the activity, just like a mojo or pojo or key value map in traditional Java applications.
The state of an activity will be saved before the activity is killed. And when it is recreated next time, Android can restore the state.
There are some cases in which the activity will be destroyed by Android. For example, you switch to another application, after some time the activity will be destroyed. When you go back, Android will recreate the activity and the onCreate method is called again.
Or when the orientation of the phone is changed, the current activity will be recreated immediately. If there are some data needs to be persisted between the transition, you can put the data in the Bundle and restore them next time. This is quite common for many applications, for example you are editing text message and a phone call is coming in, after you deal with the phone call you may wish the texting application remember your unfinished text editing.
setContentView
In Android development, the UI is described in XML, just like HTML in Web development, Android needs to load and parse the UI description file and build objects from it. After all this, the activity and the content inside it can be rendered on screen.
This is what setContentView do.
R.layout.hello_layout
One of the unusual things you will find is R.layout.hello_layout. R means Resources. All resources has an id, you will reference them by their id, all those id are defined in R class. It's an abstraction in Android to manage resources. And it's a better one. The class is automatically generated by aapt tool when building.
If you ever worked with Win32 development, you will be familiar with resource file and script, it's a DSL defined by Microsoft, resource are identified by C macros. The menus items, icons, cursors are typical resources. Every development platform and SDK has such a mechanism to manage various resources.
It's very simple easy to use after you know the rules and conventions.