Android UI(1)Getting Started - First App and Manage Activities
1. Build Your First App
Creating an Android Project
Minimum Required SDK - is the lowest version of Android that our app supports.
Target SDK - indicates the highest version of Android(also using the API level) with which you have tested with your app. As new versions of Android become available, you should test your app on the new version and update this value to match the latest API level in order to take advantage of new platform features.
Compile With - By default, this is set to the latest version of Android available in my SDK.
Theme
Build a Simple User Interface
View and ViewGroup objects.
View objects are usually UI widgets such as buttons or text fields.
ViewGroup objects are invisible view containers that define how the child views are laid out.
Create a Linear Layout
LinearLayout is a view group(a subclass of ViewGroup).
Layout in details
http://developer.android.com/guide/topics/ui/declaring-layout.html
Add a Text Field
EditText -
android:id This provides a unique identifier for the view, which you can use to reference the object from your app code.
Add String Resources
<resources> in the strings.xml
Add a Button
<Button>
android:text = "@string/button_get_json" refer the configuration to a string resource.
Respond to the Send Button
<Button>
android:onClick="sendMessage"
There should be a method in activity
public void sendMessage(View view){
…snip...
}
But in my example, EasyRestClientAndroid project, I bind the action to the button as follow:
final button buttonJson = (Button)findViewById(R.id.button_json);
buttonJson.setOnClickListener(new View.OnClickListener() {
publicvoid onClick(View v) {
new DownloadStateTask().execute(MediaType.APPLICATION_JSON);
}
});
Build an Intent
Intent is an object that provides runtime binding between separate components(such as 2 activities).
Intent will most often be used to start another activity.
Intent intent = new Intent();
intent.setClass(this, PersonListActivity.class);
startActivity(intent);
And we can also send message in intent
public final static String EXTRA_MESSAGE = "com.sillycat.easyresclienttandroid.message"
intent.putExtra(EXTRA_MESSAGE, message);
This method put the first parameter as the key, the second as the value.
Start the Second Activity
Send the intent as follow
startActivity(intent);
The System will receives this call and starts an instance of the Activity.
And the title string
<resources>
<string name="title_activity_main">EasyRestClientAndroid</string>
…snip…
In the AndroidManifest.xml
<application
android:name=".mainframe.MainApplication"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"]]>
<activity
android:name=".mainframe.MainActivity"
android:label="@string/title_activity_main">
Receive the Intent
Every Activity in invoked by an Intent, we can get that object through getIntent()
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
2. Managing the Activity Lifecycle
Download and get the file ActivityLifecycle.zip. Unzip the file. Import the project through 'Android Project from Existing Code'
Activities - foreground, background
Within the lifecycle callback methods, you can declare how your activity behaves when the user leaves and re-enters the activity. The activity will not consume system resources when I did not need them.
Starting an Activity
Understand the Lifecycle Callbacks
As the system creates a new activity instance, each callback method moves the activity state one step toward the top.
onCreate() ----> onStart() ----> onResume() --- onPause() -----> onStop ----> onRestart() -----> onDestroy()
State - Resumed, Paused, Stopped
Specify Your App's Launcher Activity
When the user selects your app icon from the Home Screen, the system calls the onCreate() method for the Activity in your app that I declared to be the "launcher" (or "main") activity.
That is the definition of Launcher Activity.
<activity
android:name=".mainframe.MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
And we can register all the other activities in the <application>
Create a New Instance
The system creates every new instance of Activity by calling its onCreate() method. Usually, the onCreate() should define the user interface and possibly instantiate some class-scope variables.
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
Check the version before we input the new codes.
Once we onCreate(), we will move on to onStart() ----> onResume()
Once other activity called, the old activity will onPause() ----> onStop()
Once we click the original activity, it will onRestart() ----> onStart() -----> onResume(), and the newly created activity B will
onPause() --> onStop() ----> onDestroy()
Destroy the Activity
The system will call onDestroy() that my instance is being completely removed from the system memory.
Pausing and Resuming an Activity
When a diagram show up, the original activity will onPause() and stay on paused. In this situation, we can also see the activity. If it is invisible, the activity should be stopped.
Pause Your Activity
Mostly, we need to do these things on onPause()
- Stop animations or other ongoing actions that could consume CPU.
- Save the draft email, something like that.
- Release system resources, such as broadcast receivers, handles to sensors(like GPS).
Example to release the camera
public void onPause(){
super.onPause();
if(mCamera != null){
mCamera.release();
mCamera = null;
}
}
Resume Your Activity
Every time we start, we call the onResume() method. We need to initialize components that we release during onPause().
Example
public void onResume(){
super.onResume();
if(mCamera == null){
initializeCamera();
}
}
Stopping and Restarting an Activity
Stop Your Activity
Start/Restart Your Activity
…snip…
Recreating an Activity
The system may destroy the activity if the user press Back or the activity finishes itself, the system's concept of that Activity instance is gone forever.
We will use an object named Bundle to store the state.
By default, the system uses the Bundle instance state to save information about each View object.
To save additional data about the activity state, we need to override the onSaveInstanceState() callback method.
Resumed ------> onSaveInstanceState() ------> Destroyed
onCreate/Created--> onRestoreInstanceState() ---> Resumed
Save Your Activity State
For instance as follow:
static final String STATE_SCORE = "playerScore"
public void onSaveInstanceStore(Bundle savedInstanceState){
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
super.onSaveInstanceState(savedInstanceState);
}
Restore Your Activity State
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if(savedInstanceState != null){
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
}
}
public void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
…same as onCreate...
}
References:
http://developer.android.com/training/basics/firstapp/creating-project.html
http://developer.android.com/training/basics/activity-lifecycle/starting.html