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);
}

Related posts:

Leave a Reply

Your email address will not be published.