4.1.1 Activity初学乍练
系统讲解 Activity 组件定位、七大生命周期回调及弹窗差异、AppCompatActivity 兼容演进、Android 5.0 持久化 onCreate、显式/隐式启动、横竖屏状态保存与常用系统 Intent 调用。
学完这一章,你能够
- 系统讲解 Activity 组件定位、七大生命周期回调及弹窗差异、AppCompatActivity 兼容演进、Android 5.0 持久化 onCreate、显式/隐式启动、横竖屏状态保存与常用系统 Intent 调用。
Activity 定位、七大生命周期与兼容基类演进
Activity 是 Android 四大组件中最核心的界面交互窗口载体,既可全屏显示,也可配置为半透明或浮动窗口,一个应用通常由多个 Activity 协作组成。其完整生命周期包含七大回调:`onCreate()`、`onStart()`、`onResume()`、`onPause()`、`onStop()`、`onRestart()` 与 `onDestroy()`。打开新的半透明/对话框风格 Activity 时旧页面仍可见,仅回调 `onPause()`;打开全屏新 Activity 使旧页面完全不可见时,会依次回调 `onPause() -> onStop()`;而普通 `AlertDialog` 与 `PopupWindow` 依附于当前 Activity 窗口,并不会触发 `onPause()` 或 `onStop()`。
在基类选择上,原生的 `Activity` 直接面向系统框架,而支持库中早期用于兼容 ActionBar 的 `ActionBarActivity` 已随 Material Design 与 `Toolbar` 的引入而废弃,现代工程(AndroidX)默认继承 `AppCompatActivity` 以获得跨版本主题与控件兼容。无论继承哪一基类,凡是创建的四大组件都必须在 `AndroidManifest.xml` 中注册声明,否则启动 Activity 时系统会直接抛出 `ActivityNotFoundException`(若类路径配置错误亦会导致类加载失败崩溃)。
双参数持久化 onCreate 与实例状态保存机制
Android 5.0(API 21)起为 `Activity` 新增了带 `PersistableBundle` 参数的重载:`onCreate(Bundle, PersistableBundle)`、`onSaveInstanceState(Bundle, PersistableBundle)` 与 `onRestoreInstanceState(Bundle, PersistableBundle)`。配合清单属性 `android:persistableMode="persistAcrossReboots"`,系统可在设备重启后恢复持久化键值。日常开发中,当按下 Home 键、锁屏、跳转新页面或发生横竖屏切换等可能被系统未经主动退出即回收的场景时,系统会回调 `onSaveInstanceState()` 供保存临时界面数据;页面重建后既可在 `onCreate(Bundle)` 中判空取出,也可在 `onStart()` 与 `onResume()` 之间的 `onRestoreInstanceState(Bundle)` 中统一恢复。
启动 Activity 的多种方式、横竖屏适配与系统组件调用
启动 Activity 分为显式启动与隐式启动:显式启动直接指定目标组件类,常见写法包括 `new Intent(Current.this, Target.class)`、构造 `ComponentName(pkg, cls)` 配合 `intent.setComponent(cn)`,以及调用 `intent.setClassName(pkg, cls)`(注意第一个参数应为应用包名而非当前 Activity 类名);若要拉起外部应用入口页,可通过 `getPackageManager().getLaunchIntentForPackage(packageName)` 获取启动 Intent 并判空后调用 `startActivity()`。隐式启动则不指定类名,而由系统按 `Action`、`Category` 与 `Data` 匹配清单中的 `<intent-filter>`。
默认情况下横竖屏旋转会触发 Activity 完整销毁重建:`onPause -> onStop -> onDestroy -> onCreate -> onStart -> onResume`,未保存的控件状态会重置。可通过三种方式处理:一是在 `<activity>` 中设置 `android:screenOrientation` 锁定方向(支持 `unspecified`、`landscape`、`portrait`、`user`、`behind`、`sensor`、`nosensor` 七种常用取值);二是准备 `res/layout-land` 与 `res/layout-port` 同名布局自动切换,或在 `onCreate()` 中检查 `getResources().getConfiguration().orientation` 动态加载布局;三是通过 `onSaveInstanceState()` 写入 `Bundle`(如 `outState.putInt("num", 1)`)并在重建时判空读取恢复。本地模拟器调试旋转时可按快捷键 `Ctrl + F11/F12` 或模拟器工具栏旋转按钮。
Android 还内置了大量标准系统 Activity 入口,开发者可通过构造标准 `Intent` 与 `Uri` 直接唤起拨号(`ACTION_DIAL` + `tel:`)、发短信(`ACTION_SENDTO` + `smsto:`)、发彩信/附件(`ACTION_SEND` + `EXTRA_STREAM`)、浏览器(`ACTION_VIEW` + `http://`)、邮件(`mailto:`)、地图定位与路径规划(`geo:`)、多媒体播放、系统拍照(`MediaStore.ACTION_IMAGE_CAPTURE`)、应用商店(`market://`)、系统设置(`Settings.ACTION_WIRELESS_SETTINGS`)、应用卸载(`ACTION_DELETE` + `package:`)与联系人查看。在 Android 7.0+ 跨应用共享文件或拍照输出路径时,应使用 `FileProvider` 生成 `content://` URI 替代传统 `Uri.fromFile()`。
运行 Activity 七大生命周期状态机、横竖屏状态持久化与显式/系统 Intent 验证
"""Offline Android Activity 7-callback lifecycle, orientation state persistence, and launch verifier."""
import json
VERSION = "CPython 3.12.14 offline Android component/IPC/Fragment verifier (Android SDK/emulator absent)"
class SimulatedActivity:
"""Models Android Activity 7 lifecycle callbacks plus saved/persistable state."""
def __init__(self, name: str, persist_across_reboots: bool = False):
self.name = name
self.persist_across_reboots = persist_across_reboots
self.state = "INITIAL"
self.trace = []
self.bundle = {}
self.persistable_bundle = {}
def create(self, saved_state: dict | None = None, persist_state: dict | None = None):
self.state = "CREATED"
if self.persist_across_reboots and persist_state is not None:
self.trace.append("onCreate(savedInstanceState, persistentState)")
self.bundle.update(saved_state or {})
self.persistable_bundle.update(persist_state)
else:
self.trace.append("onCreate")
if saved_state:
self.bundle.update(saved_state)
def start(self):
self.state = "STARTED"
self.trace.append("onStart")
def restore_instance_state(self, saved_state: dict, persist_state: dict | None = None):
if saved_state:
self.bundle.update(saved_state)
if self.persist_across_reboots and persist_state is not None:
self.persistable_bundle.update(persist_state)
self.trace.append("onRestoreInstanceState(savedInstanceState, persistentState)")
else:
self.trace.append("onRestoreInstanceState")
def resume(self):
self.state = "RESUMED"
self.trace.append("onResume")
def pause(self):
self.state = "PAUSED"
self.trace.append("onPause")
def save_instance_state(self, out_state: dict, out_persist: dict | None = None):
out_state.update(self.bundle)
if self.persist_across_reboots and out_persist is not None:
out_persist.update(self.persistable_bundle)
self.trace.append("onSaveInstanceState(outState, outPersistentState)")
else:
self.trace.append("onSaveInstanceState")
def stop(self):
self.state = "STOPPED"
self.trace.append("onStop")
def restart(self):
self.state = "RESTARTING"
self.trace.append("onRestart")
def destroy(self):
self.state = "DESTROYED"
self.trace.append("onDestroy")
def show_alert_dialog(self):
# AlertDialog / PopupWindow attach to same Activity window; no lifecycle transition occurs
return self.state
def case_activity_seven_callback_lifecycle():
act = SimulatedActivity("MainActivity")
# Cold start
act.create()
act.start()
act.resume()
# AlertDialog does not pause/stop Activity
state_after_dialog = act.show_alert_dialog()
# Transparent / dialog-themed Activity opens on top -> only onPause
act.pause()
act.resume()
# Full-screen Activity covers it -> onPause + onStop; then user presses Back -> onRestart + onStart + onResume
act.pause()
act.stop()
act.restart()
act.start()
act.resume()
# Finish
act.pause()
act.stop()
act.destroy()
actual = {
"state_after_dialog": state_after_dialog,
"final_state": act.state,
"callback_trace": act.trace,
}
expected = {
"state_after_dialog": "RESUMED",
"final_state": "DESTROYED",
"callback_trace": [
"onCreate", "onStart", "onResume",
"onPause", "onResume",
"onPause", "onStop",
"onRestart", "onStart", "onResume",
"onPause", "onStop", "onDestroy",
],
}
return {
"name": "activity_seven_callback_lifecycle",
"summary": "验证 Activity 七大生命周期回调顺序,以及 AlertDialog 不触发 onPause/onStop、半透明弹窗仅触发 onPause、全屏跳转触发 onStop 与返回触发 onRestart。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_orientation_change_and_state_persistence():
old_act = SimulatedActivity("MainActivity", persist_across_reboots=True)
old_act.create({}, {})
old_act.start()
old_act.resume()
old_act.bundle["num"] = 1
old_act.persistable_bundle["draft_id"] = "doc-42"
saved, persisted = {}, {}
old_act.pause()
old_act.save_instance_state(saved, persisted)
old_act.stop()
old_act.destroy()
new_act = SimulatedActivity("MainActivity", persist_across_reboots=True)
new_act.create(saved, persisted)
new_act.start()
new_act.restore_instance_state(saved, persisted)
new_act.resume()
def select_layout(orientation: str) -> str:
return "layout-land/activity_main.xml" if orientation == "ORIENTATION_LANDSCAPE" else "layout-port/activity_main.xml"
orientations = ["unspecified", "landscape", "portrait", "user", "behind", "sensor", "nosensor"]
actual = {
"old_trace": old_act.trace[-4:],
"new_trace": new_act.trace,
"restored_num": new_act.bundle.get("num"),
"restored_persist_draft": new_act.persistable_bundle.get("draft_id"),
"land_layout": select_layout("ORIENTATION_LANDSCAPE"),
"port_layout": select_layout("ORIENTATION_PORTRAIT"),
"screen_orientation_modes_count": len(orientations),
}
expected = {
"old_trace": ["onPause", "onSaveInstanceState(outState, outPersistentState)", "onStop", "onDestroy"],
"new_trace": [
"onCreate(savedInstanceState, persistentState)",
"onStart",
"onRestoreInstanceState(savedInstanceState, persistentState)",
"onResume",
],
"restored_num": 1,
"restored_persist_draft": "doc-42",
"land_layout": "layout-land/activity_main.xml",
"port_layout": "layout-port/activity_main.xml",
"screen_orientation_modes_count": 7,
}
return {
"name": "orientation_change_and_state_persistence",
"summary": "验证横竖屏重建时的 Bundle 与 API 21+ PersistableBundle 状态保存恢复、layout-land/layout-port 布局切换及 7 种 screenOrientation 取值。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_explicit_implicit_launch_and_system_intents():
manifest_activities = {
"com.demo.app.MainActivity",
"com.demo.app.SecondActivity",
}
def launch_explicit(component_cls: str) -> str:
if component_cls not in manifest_activities:
return "ActivityNotFoundException"
return f"LAUNCHED:{component_cls}"
system_intents = {
"dial": ("android.intent.action.DIAL", "tel:10086"),
"sms": ("android.intent.action.SENDTO", "smsto:10086"),
"browser": ("android.intent.action.VIEW", "https://example.org"),
"mail": ("android.intent.action.SENDTO", "mailto:someone@domain.com"),
"map": ("android.intent.action.VIEW", "geo:39.9,116.3"),
"market": ("android.intent.action.VIEW", "market://details?id=com.demo.app"),
"camera": ("android.media.action.IMAGE_CAPTURE", None),
"settings": ("android.settings.WIRELESS_SETTINGS", None),
}
actual = {
"launch_declared": launch_explicit("com.demo.app.SecondActivity"),
"launch_undeclared": launch_explicit("com.demo.app.UnregisteredActivity"),
"system_intent_count": len(system_intents),
"dial_uri_scheme": system_intents["dial"][1].split(":")[0],
"geo_uri_scheme": system_intents["map"][1].split(":")[0],
}
expected = {
"launch_declared": "LAUNCHED:com.demo.app.SecondActivity",
"launch_undeclared": "ActivityNotFoundException",
"system_intent_count": 8,
"dial_uri_scheme": "tel",
"geo_uri_scheme": "geo",
}
return {
"name": "explicit_implicit_launch_and_system_intents",
"summary": "验证显式启动与 AndroidManifest 注册校验(未注册触发 ActivityNotFoundException)及常见系统 Intent/URI 构造。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_activity_seven_callback_lifecycle(),
case_orientation_change_and_state_persistence(),
case_explicit_implicit_launch_and_system_intents(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 验证冷启动/弹窗/全屏覆盖/返回/销毁回调顺序、Bundle 与 PersistableBundle 重建恢复、清单注册校验与系统 URI 构造。
所需环境:Windows x64、CPython 3.12.14 离线 Android 组件/生命周期/IPC/Fragment 确定性验证环境(本地未安装 Android SDK/Gradle/ADB/模拟器)。
当前源码 SHA256:7daf98085336c06ea8f83cbb0ceeb66597d455862eee74fbed012cdcb2d1270f
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Android 组件/生命周期/IPC/Fragment 确定性验证环境(本地未安装 Android SDK/Gradle/ADB/模拟器)。
ZIP SHA256:236dedd16f6ccce876b5bff63ddf845fdbb5e851d7dbd32b3a73cdcfc3fc56c0
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Activity 上弹出 AlertDialog 与启动一个对话框风格的透明 Activity,两者对原 Activity 生命周期的影响有何不同?
展开参考解答
AlertDialog 属于当前 Activity 窗口体系,不会触发 onPause() 或 onStop();而透明/对话框风格的新 Activity 会夺走焦点但原页面仍部分可见,因此原 Activity 会回调 onPause() 但不回调 onStop()。