Android:Managing the Activity Lifecycle

Managing the Activity Lifecycle
活动生命周期管理
 
指定APP启动活动
 
//在AndroidManifest.xml下填写,ECLIPSE可以自动创建
<activity android:name=".MainActivity" android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
 
//创建一个实例:系统会在所有的活动启动时,调用onCreate()方法
TextView mTextView; // Member variable for text view in the layout
 
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
 
    // Set the user interface layout for this Activity
    // The layout file is defined in the project res/layout/main_activity.xml file
    setContentView(R.layout.main_activity); //根据main_activity.xml设计好的界面设置用户界面
 
    // Initialize member TextView so we can manipulate it later
    mTextView = (TextView) findViewById(R.id.text_message);//获取用户输入id=text_message的内容
 
    // Make sure we're running on Honeycomb or higher to use ActionBar APIs
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { //如果SDK版本大于等于安卓3.0
        // For the main activity, make sure the app icon in the action bar
        // does not behave as a button
        ActionBar actionBar = getActionBar();
        actionBar.setHomeButtonEnabled(false);
    }
}
 
onCreate方法执行完之后立即执行onStart,onResume
 
//销毁活动,大多数不需要onDestroy,只需onPause或者onStop
@Override
public void onDestroy() {
    super.onDestroy();  // Always call the superclass
 
    // Stop method tracing that the activity started during onCreate()
    android.os.Debug.stopMethodTracing();
}
 
//暂停和恢复一个活动(onPause,onResume)
@Override
public void onPause() {
    super.onPause();  // Always call the superclass method first
 
    // Release the Camera because we don't need it when paused
    // and other activities might need to use it.
    if (mCamera != null) {
        mCamera.release()
        mCamera = null;
    }
}
 
@Override
public void onResume() {
    super.onResume();  // Always call the superclass method first
 
    // Get the Camera instance as the activity achieves full user focus
    if (mCamera == null) {
        initializeCamera(); // Local method to handle camera init
    }
}
 
//停止和重启一个活动(onStop,onRestart)
无论什么情况下程序终止,都会先调用onPause,然后再调用onStop
@Override
protected void onStop() {
    super.onStop();  // Always call the superclass method first
 
    // Save the note's current draft, because the activity is stopping
    // and we want to be sure the current note progress isn't lost.
    ContentValues values = new ContentValues();
    values.put(NotePad.Notes.COLUMN_NAME_NOTE, getCurrentNoteText());
    values.put(NotePad.Notes.COLUMN_NAME_TITLE, getCurrentNoteTitle());
 
    getContentResolver().update(
            mUri,    // The URI for the note to update.
            values,  // The map of column names and new values to apply to them.
            null,    // No SELECT criteria are used.
            null     // No WHERE columns are used.
            );
}
 
@Override
protected void onStart() {
    super.onStart();  // Always call the superclass method first
 
    // The activity is either being restarted or started for the first time
    // so this is where we should make sure that GPS is enabled
    LocationManager locationManager = 
            (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
 
    if (!gpsEnabled) {
        // Create a dialog here that requests the user to enable GPS, and use an intent
        // with the android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS action
        // to take the user to the Settings screen to enable GPS when they click "OK"
    }
}
 
@Override
protected void onRestart() {
    super.onRestart();  // Always call the superclass method first
 
    // Activity being restarted from stopped state    
}
 
//重新创建活动
 
保存活动状态
static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
...
 
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
    savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
 
    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}
 
回复活动状态(必须先检测)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); // Always call the superclass first
 
    // Check whether we're recreating a previously destroyed instance
    if (savedInstanceState != null) {
        // Restore value of members from saved state
        mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
        mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
    } else {
        // Probably initialize members with default values for a new instance
    }
    ...
}
也可以不检测
public void onRestoreInstanceState(Bundle savedInstanceState) {
    // Always call the superclass so it can restore the view hierarchy
    super.onRestoreInstanceState(savedInstanceState);
 
    // Restore state members from saved instance
    mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
    mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
}

android:building your first app

AndroidManifest.xml
The manifest file describes the fundamental characteristics of the app and defines each of its components. You'll learn about various declarations in this file as you read more training classes.
src/
Directory for your app's main source files. By default, it includes an Activity class that runs when your app is launched using the app icon.
res/
Contains several sub-directories for app resources. Here are just a few:
drawable-hdpi/
Directory for drawable objects (such as bitmaps) that are designed for high-density (hdpi) screens. Other drawable directories contain assets designed for other screen densities(密度).
layout/(用户界面)
Directory for files that define your app's user interface.
values/(存储变量值)
Directory for other various XML files that contain a collection of resources, such as string and color definitions.
 
//创建一个activity_main.xml,match_parent代表着充满整个屏幕
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
</LinearLayout>
<!-- 
首次定义一个id需要用 @+id/message相当于form表单中的id="message"
android:hint代表这默认的文本框为空时填写的内容
@string/edit_message表示从string.xml中取出名为edit_message的字段值
wrap_content代表充满view
下面为一个文本框和一个按钮
-->
<EditText android:id="@+id/edit_message"
        android:layout_width="wrap_content" <!-- 可改为0 -->
        android:layout_height="wrap_content" <!-- 可改为0dp -->
        android:hint="@string/edit_message" />
<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_send" 
		android:onClick="sendMessage"/> <!-- 点击时,调用MainActivity.java下的sendMessage方法 -->
 
//创建一个strings.xml放在res/values下,用来存储变量值
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">My First App</string>
    <string name="edit_message">Enter a message</string>
    <string name="button_send">Send</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
</resources>
 
//创建一个MainActivity.java在src/com.exmple.my/下面
package com.example.my.first.app;
 
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
 
public class MainActivity extends Activity {
	//为了intent.putExtra方法的使用,必须现在这里定义EXTRA_MESSAGE
	public final static String EXTRA_MESSAGE = "com.example.my.MESSAGE";
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
	//必须是公共的,有void返回值,view作为唯一的参数
	public void sendMessage(View view) {
		//intent是一个对象,经常被用来启动另一个活动
		//第一个参数为this,第二个为要启动的活动
		Intent intent = new Intent(this, DisplayMessageActivity.class);
 
		//intent还可以将数据传递给要调用的activity
		//根据id获取输入的内容
    	EditText editText = (EditText) findViewById(R.id.edit_message);
 
		//赋值给message
    	String message = editText.getText().toString();
 
		//putExtra的参数相当于key,value
    	intent.putExtra(EXTRA_MESSAGE, message);
 
    	//开始activity
    	startActivity(intent);
	}
}
 
//创建一个DisplayMessageActivity.java在src/com.exmple.my/下面
package com.example.my;
 
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
 
public class DisplayMessageActivity extends Activity 
{
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        //所有的Activity必须继承父Activity的onCreate方法
 
        // Get the message from the intent
        Intent intent = getIntent();
        String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
 
        // Create the text view
        TextView textView = new TextView(this);
        textView.setTextSize(40);
        textView.setText(message);
 
        //为活动布局设置文本视图
        setContentView(textView);
    }
}