获取运行中进程的 pid 映射:package -> pid 优先 pidof(快),不行再回退 ps。
()
| 558 | |
| 559 | |
| 560 | def _get_pid_map() -> Dict[str, int]: |
| 561 | """ |
| 562 | 获取运行中进程的 pid 映射:package -> pid |
| 563 | 优先 pidof(快),不行再回退 ps。 |
| 564 | """ |
| 565 | pid_map: Dict[str, int] = {} |
| 566 | # 方案 A:pidof(Android 8+ 大多支持) |
| 567 | # pidof 可能返回多个 pid(多进程),这里取第一个 |
| 568 | # 但我们需要逐包调用 pidof,太慢,所以改用 ps 做一次性扫描更划算。 |
| 569 | # 因此优先方案 B:ps -A 解析。 |
| 570 | ps_out = run_su_command("ps -A -o PID,NAME") |
| 571 | # 输出示例: |
| 572 | # PID NAME |
| 573 | # 123 com.xxx.yyy |
| 574 | for line in ps_out.splitlines()[1:]: |
| 575 | line = line.strip() |
| 576 | if not line: |
| 577 | continue |
| 578 | parts = re.split(r"\s+", line, maxsplit=1) |
| 579 | if len(parts) != 2: |
| 580 | continue |
| 581 | pid_s, name = parts |
| 582 | if name.startswith("com."): # 简单过滤:只收集 app 进程 |
| 583 | try: |
| 584 | pid_map[name] = int(pid_s) |
| 585 | except ValueError: |
| 586 | pass |
| 587 | return pid_map |
| 588 | |
| 589 | |
| 590 | def _get_app_label_fast(pkg: str) -> Optional[str]: |
nothing calls this directly
no test coverage detected