feat(android): detect foreground package via adb dumpsys

This commit is contained in:
pj committed 2026-05-28 11:21:14 +05:30
1 parent 4d26bdf00d
commit 09528d84e6
2 files changed
+69

No files matched your search

+33
View File
@@ -8,6 +8,7 @@ import (
"os"
"os/exec"
"path/filepath"
"regexp"
"slices"
"strings"
"time"
@@ -236,6 +237,38 @@ func waitForBoot(ctx context.Context, timeout time.Duration) error {
}
}
// ForegroundPackage returns the package of the currently resumed activity on
// the connected device, or "" when it cannot be determined.
func ForegroundPackage(ctx context.Context) (string, error) {
adb, err := AdbBinary()
if err != nil {
return "", err
}
output, err := exec.CommandContext(ctx, adb, "shell", "dumpsys", "activity", "activities").Output()
if err != nil {
return "", err
}
return parseForegroundPackage(string(output)), nil
}
// resumedActivityPackage matches the "<package>/<activity>" component name that
// dumpsys prints on ResumedActivity lines, capturing the package.
var resumedActivityPackage = regexp.MustCompile(`([a-zA-Z][a-zA-Z0-9_.]*)/[a-zA-Z0-9_.$]+`)
// parseForegroundPackage extracts the foreground package from `dumpsys activity
// activities` output by reading the first ResumedActivity component name.
func parseForegroundPackage(dumpsys string) string {
for line := range strings.SplitSeq(dumpsys, "\n") {
if !strings.Contains(line, "ResumedActivity") {
continue
}
if match := resumedActivityPackage.FindStringSubmatch(line); match != nil {
return match[1]
}
}
return ""
}
func bootCompleted(ctx context.Context) (bool, error) {
adb, err := AdbBinary()
if err != nil {