蓝色天空.知识 · 实践 · 创造
我的收藏
Android 教程目录 156章
课程介绍
Android / LEARN BY DOING

4.1.2 Activity初窥门径

掌握 Activity 间单向传参与双向结果回传、当前页面定位与 ActivityCollector 批量关闭、双击返回退出、过场动画与全屏/对话框主题配置,以及 Bundle 传输上限与 onWindowFocusChanged 用法。

学完这一章,你能够

  • 掌握 Activity 间单向传参与双向结果回传、当前页面定位与 ActivityCollector 批量关闭、双击返回退出、过场动画与全屏/对话框主题配置,以及 Bundle 传输上限与 onWindowFocusChanged 用法。

Activity 间数据传递、双向回传与 Bundle 上限

多页面协作的基础是组件间通信:单向传参可通过 `Intent.putExtra()` 或打包 `Bundle` 后调用 `putExtras()` 传递基础数据,目标页经 `getIntent().getExtras()` 取出;当需要后一页面将选择结果返回前一页面时,经典做法是调用 `startActivityForResult(intent, requestCode)`,目标页结束前通过 `setResult(RESULT_OK, resultIntent)` 回写数据并 `finish()`,原页面在 `onActivityResult(requestCode, resultCode, data)` 中按请求码与结果码分流处理(现代 Jetpack 推荐改用类型安全的 `registerForActivityResult` 与 `ActivityResultContracts`)。无论单向还是回传,都必须注意 Binder IPC 事务缓冲区总大小受限(单进程共享 1MB,单次 `Bundle` 建议严格控制在 0.5MB 以内),否则会抛出 `TransactionTooLargeException`。

页面追踪、ActivityCollector 一键关闭与双击返回退出

在大型项目中快速定位当前界面,可在公共 `BaseActivity` 的 `onCreate()` 中打印 `getClass().getSimpleName()`,或通过配置好 SDK 环境变量的命令行执行 `adb shell dumpsys activity` 查看任务栈详情。若需在任意页面一键关闭所有已打开页面,可维护一个 `ActivityCollector` 工具类,用集合在 `onCreate()`/`onDestroy()` 中增删引用,并在 `finishAll()` 中遍历检查 `!activity.isFinishing()` 后逐个 `finish()`。需要彻底结束进程时传统做法还会结合 `ActivityManager.killBackgroundProcesses()` 与 `System.exit(0)`(现代 Android 推荐优先依赖 `finishAffinity()` 与系统生命周期托管,避免粗暴强杀进程破坏状态恢复)。

防止误触返回键直接退出应用,常见有两类“2 秒内再按一次退出”实现:其一定义布尔标记 `isExit`,首次按 `KEYCODE_BACK` 时置 `true` 并弹出提示,同时借助 `Handler.sendEmptyMessageDelayed(0, 2000)` 在 2 秒后复位;其二更简洁且无 `Handler` 内存泄漏风险,仅记录上次点击时间戳 `exitTime`,再次按下时比较 `System.currentTimeMillis() - exitTime > 2000`,超时则刷新时间并提示,否则执行退出。使用命令行排查页面栈状态时同样可借助 `adb shell dumpsys activity` 核对当前栈顶 Activity。

过场动画、全屏隐藏标题栏、焦点测量与对话框风格

为 Activity 切换添加过渡动画有两种经典方式:一是紧跟 `startActivity()` 或 `finish()` 调用 `overridePendingTransition(enterAnim, exitAnim)`(Android 14+ 推荐改用 `overrideActivityTransition`);二是在 `styles.xml` 中自定义继承 `@android:style/Animation.Activity` 的动画样式并挂到全局 `AppTheme` 的 `android:windowAnimationStyle` 上,其四个属性分别控制 A 跳 B 时 B 进入(`activityOpenEnterAnimation`)、A 退出(`activityOpenExitAnimation`),以及 B 返回 A 时 A 进入(`activityCloseEnterAnimation`)、B 退出(`activityCloseExitAnimation`)。API 19+ 还可采用 `TransitionManager` 或共享元素转场实现更丰富的页面动效。

设置无标题栏或全屏有三种途径:代码调用 `getActionBar().hide()`(或 `getSupportActionBar().hide()`)、在 `setContentView()` 之前调用 `requestWindowFeature(Window.FEATURE_NO_TITLE)`(继承 `AppCompatActivity` 时常直接改用 `Theme.AppCompat.NoActionBar` 避免特性冲突),或在清单 `<activity>` 中指定 `@android:style/Theme.NoTitleBar.FullScreen`。若需确认界面已完成初次绘制与布局测量,可覆写 `onWindowFocusChanged(boolean hasFocus)`,在窗口获得焦点时安全读取控件宽高。若要将 Activity 呈现为悬浮对话框外观,只需在清单配置 `android:theme="@android:style/Theme.Dialog"`(AppCompat 下对应 `Theme.AppCompat.Dialog`),并可按需设置标题与窗口图标。

运行 Activity Bundle 往返、ActivityCollector 批量退出与过渡动画/窗口配置验证

含完整源码 · 164 行
展开查看收起
python
"""Offline Android Activity data passing, result roundtrip, ActivityCollector, and window config verifier."""
import json

VERSION = "CPython 3.12.14 offline Android component/IPC/Fragment verifier (Android SDK/emulator absent)"


def case_activity_bundle_pass_and_result_roundtrip():
    # Models ActivityTest1 (one-way Bundle) + ActivityTest2 (startActivityForResult -> setResult -> onActivityResult)
    max_safe_bundle_bytes = 512 * 1024  # 0.5 MB safe threshold below 1 MB Binder transaction buffer

    def send_bundle(payload: dict) -> tuple[bool, str]:
        encoded = json.dumps(payload, ensure_ascii=False).encode("utf-8")
        if len(encoded) >= max_safe_bundle_bytes:
            return False, "TransactionTooLargeException"
        return True, "OK"

    one_way_bundle = {"user": "Alice", "age": 22}
    ok_small, status_small = send_bundle(one_way_bundle)
    ok_large, status_large = send_bundle({"blob": "x" * (600 * 1024)})

    # Two-way result callback
    request_code = 101
    result_code = -1  # Activity.RESULT_OK
    returned_bundle = {"selected_city": "Hangzhou"}
    received = None
    if request_code == 101 and result_code == -1:
        received = returned_bundle["selected_city"]

    actual = {
        "small_bundle_ok": ok_small,
        "small_bundle_status": status_small,
        "oversize_bundle_ok": ok_large,
        "oversize_bundle_status": status_large,
        "result_roundtrip_city": received,
    }
    expected = {
        "small_bundle_ok": True,
        "small_bundle_status": "OK",
        "oversize_bundle_ok": False,
        "oversize_bundle_status": "TransactionTooLargeException",
        "result_roundtrip_city": "Hangzhou",
    }
    return {
        "name": "activity_bundle_pass_and_result_roundtrip",
        "summary": "验证 Activity 单向 Bundle 传参、startActivityForResult/onActivityResult 双向回传,以及超过 0.5MB 阈值的 TransactionTooLargeException 防护。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_activity_collector_and_double_back_exit():
    class FakeActivity:
        def __init__(self, cls_name: str):
            self.cls_name = cls_name
            self.finishing = False

        def finish(self):
            self.finishing = True

    collector: list[FakeActivity] = []
    for name in ("LoginActivity", "HomeActivity", "DetailActivity"):
        collector.append(FakeActivity(name))
    current_class_log = collector[-1].cls_name
    finished_names = []
    for act in collector:
        if not act.finishing:
            act.finish()
            finished_names.append(act.cls_name)
    collector.clear()

    # Double-back exit via timestamp diff (2000 ms window)
    def simulate_double_back(tap_times_ms: list[int], window_ms: int = 2000) -> list[str]:
        exit_time = 0
        actions = []
        for t in tap_times_ms:
            if (t - exit_time) > window_ms:
                actions.append("TOAST_AGAIN")
                exit_time = t
            else:
                actions.append("EXIT_APP")
        return actions

    actual = {
        "current_class_log": current_class_log,
        "finished_all": finished_names,
        "remaining_after_clear": len(collector),
        "double_back_within_2s": simulate_double_back([10000, 11200]),
        "double_back_over_2s": simulate_double_back([10000, 12500, 13400]),
    }
    expected = {
        "current_class_log": "DetailActivity",
        "finished_all": ["LoginActivity", "HomeActivity", "DetailActivity"],
        "remaining_after_clear": 0,
        "double_back_within_2s": ["TOAST_AGAIN", "EXIT_APP"],
        "double_back_over_2s": ["TOAST_AGAIN", "TOAST_AGAIN", "EXIT_APP"],
    }
    return {
        "name": "activity_collector_and_double_back_exit",
        "summary": "验证 BaseActivity 当前类名追踪、ActivityCollector 一键关闭全部页面,以及 2000ms 双击返回退出时间窗判定。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_transition_animation_fullscreen_dialog_theme():
    style_animation_slots = {
        "activityOpenEnterAnimation": "B_enter_on_A_to_B",
        "activityOpenExitAnimation": "A_exit_on_A_to_B",
        "activityCloseEnterAnimation": "A_enter_on_B_back_to_A",
        "activityCloseExitAnimation": "B_exit_on_B_back_to_A",
    }

    def check_no_title_order(calls: list[str]) -> str:
        idx_req = calls.index("requestWindowFeature(FEATURE_NO_TITLE)")
        idx_set = calls.index("setContentView")
        return "OK" if idx_req < idx_set else "AndroidRuntimeException"

    # onWindowFocusChanged(hasFocus=True) fires after view tree is measured
    focus_measurements = []
    for has_focus, measured_w in ((True, 1080), (False, 1080)):
        if has_focus:
            focus_measurements.append(measured_w)

    actual = {
        "animation_slot_count": len(style_animation_slots),
        "open_enter_target": style_animation_slots["activityOpenEnterAnimation"],
        "no_title_before_set_content": check_no_title_order(["requestWindowFeature(FEATURE_NO_TITLE)", "setContentView"]),
        "no_title_after_set_content": check_no_title_order(["setContentView", "requestWindowFeature(FEATURE_NO_TITLE)"]),
        "focus_measured_width": focus_measurements,
        "dialog_theme": "@android:style/Theme.Dialog",
        "dumpsys_cmd": "adb shell dumpsys activity",
    }
    expected = {
        "animation_slot_count": 4,
        "open_enter_target": "B_enter_on_A_to_B",
        "no_title_before_set_content": "OK",
        "no_title_after_set_content": "AndroidRuntimeException",
        "focus_measured_width": [1080],
        "dialog_theme": "@android:style/Theme.Dialog",
        "dumpsys_cmd": "adb shell dumpsys activity",
    }
    return {
        "name": "transition_animation_fullscreen_dialog_theme",
        "summary": "验证 Activity 四项全局过场动画槽位、requestWindowFeature 调用时序、onWindowFocusChanged 获取测量宽度与对话框主题配置。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_activity_bundle_pass_and_result_roundtrip(),
        case_activity_collector_and_double_back_exit(),
        case_transition_animation_fullscreen_dialog_theme(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
验证单向/双向传参与 0.5MB 阈值防护、ActivityCollector 与 2000ms 双击退出窗口、4 项过渡动画槽位及 requestWindowFeature 调用顺序。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1834.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Android

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1834.zip

下载课程关联工程包:Android

课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

Android 进程间 Binder 事务缓冲区上限约为 1MB(多事务共享),单次 Bundle 超过约 0.5MB 即可能触发 TransactionTooLargeException;大数据应改为落盘文件、SQLite/Room 数据库或共享 ViewModel/Repository,仅经 Intent 传递轻量的 ID 或 URI。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习