Activity是Android最常用最基本的四大组件之一,Activity是一个应用程序组件,提供一个屏幕,用户可以用来交互完成某项操作。
Activity中的所有操作都跟用户有关系,是一个跟用户交互的组件,可以通过SetContentView(View)来显示指定控件。
- Activity生命周期
Acivity一共有七个生命周期:
一般简单的生命周期:onCreate()->onStart()->onResume()->onPause()->onStop()->onDestory()
启动Activity:onCreate()->onStart()->onResume()
当前Activity被覆盖:onPause()
当Activity由覆盖回到前台:onResume()
当Activity转到新的Activity界面:onPause()->onStop()
->onDestory()
用户后退到此Activity:onRestart()->onStart()->onResume()
package com.appress.gerber.myapplication;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "LifeCycleActivity";
private Context mContext = this;
private int param = 1;
//Activity创建时被调用
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG,"onCreated");
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext,TargetActivity.class);
startActivity(intent);
}
});
}
//Activity创建或从后台重新回到前台被调用
@Override
protected void onStart() {
super.onStart();
Log.i(TAG,"onStart");
}
//Activity从后台重新回到前台时被调用
@Override
protected void onRestart() {
super.onRestart();
Log.i(TAG,"onRestart");
}
//Activity创建或者从覆盖、后台回到前台被调用
@Override
protected void onResume() {
super.onResume();
Log.i(TAG,"onResume");
}
//被覆盖到下面或者被锁屏
@Override
protected void onPause() {
super.onPause();
Log.i(TAG,"onPause");
}
//退出当前Activity或者跳转到新的Activity
@Override
protected void onStop() {
super.onStop();
Log.i(TAG,"onStop");
}
//退出当前Activity,调用之后Activity就结束了
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG,"onDestory");
}
/**
* Activity被系统杀死之后调用
* 屏幕方向改变时,Activity被销毁在重建;
* 在onPause之前使用
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt("param",param);
Log.i(TAG,"onSaveInstanceState:"+ param);
super.onSaveInstanceState(outState);
}
/**
*Activity被系统杀死后又被重新创建
*屏幕方向改变时,Activity被销毁再重建;
* 在onStart之后
*/
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
param = savedInstanceState.getInt("param");
Log.i(TAG,"onRestoreInstanceState" + param);
super.onRestoreInstanceState(savedInstanceState);
}
}
结果:
1. 启动Activity:
2. 跳转到其他页面(Home键退回):
3. 从其他页面返回(从后台到前台):
4. 销毁Activity
5. 横竖屏切换
在做横竖屏切换时,onSaveInstanceState保存了临时数据,切换完毕后onRestoreInstanceState取出刚刚保存的数据。