1 生命周期图
- onCreate():页面创建
- onStart():页面可见,但不交互
- onResume():页面可见,且交互
- onPause(): 页面不能交互
- onStop() : 页面不可见
- onDestory() 页面销毁
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
2 Activity 之间的跳转
- 显示
- 隐式
2.1 显示跳转
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="跳转"
android:onClick="jumpToSetting"
android:textSize="20sp" />
public void jumpToSetting(View view) {
/*从 MainActivity.this 到 SettingActivity.class*/
Intent intent = new Intent(MainActivity.this, SettingActivity.class);
/*跳转*/
startActivity(intent);
}
2.2 隐式跳转
activity / category / data
- 过滤标签
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
public void toCustom(View view) {
Intent intent = new Intent();
intent.setAction("com.example.activity.SettingActivity");
startActivity(intent);
}
<activity
android:name=".SettingActivity"
android:exported="false">
<intent-filter>
<action android:name="com.example.activity.SettingActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
public void toBaidu(View view) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW); // android.intent.action.VIEW
intent.setData(Uri.parse("http://www.baidu.com"));
startActivity(intent);
}
3 多页面情况下 activity 生命周期
home主页面 与 set 页面交互
-
启动该app
-
跳转到 设置页面
-
返回到 home页面
-
退出app前夕
-
关闭该app
点击返回键,退出app,然后再点图标回来
点击home键,回到桌面,然后再点击图标回来
- 系统桌面也是一个app
- 不会onDstroy()
页面复用
弹出对话框
- 对话框依附于activity
- 不影响生命周期
<Button
android:id="@+id/btn_pop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="弹出对话框"
android:onClick="popDialog"
android:textSize="20sp" />
public void popDialog(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("温馨提示");
builder.setMessage("你好啊");
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.setPositiveButton("确认", null);
AlertDialog alertDialog = builder.create();
alertDialog.show();
}