app: Add app related features

This commit is contained in:
2025-10-13 20:19:45 +02:00
parent 4304a92a53
commit 40af079fd2

61
app.go Normal file
View File

@@ -0,0 +1,61 @@
package goadb
import (
"fmt"
"regexp"
"strconv"
"strings"
)
// Get the current focussed app package name
func (d *Device) GetCurrentAppPackage() (string, error) {
data, err := d.RunCommand("shell dumpsys activity activities | grep ResumedActivity")
re := regexp.MustCompile(`\b([a-zA-Z0-9._]+)/(?:[a-zA-Z0-9._]+)\b`)
matches := re.FindStringSubmatch(string(data))
if len(matches) > 1 {
return matches[1], nil
} else {
return "", nil
}
return "", err
}
// Get the pid for a app
func (d *Device) GetAppPid(appackage string) (int, error) {
data, err := d.RunCommand(fmt.Sprintf("shell pidof %s"))
if err != nil {
return -1, err
}
pid, err := strconv.Atoi(strings.TrimSpace(string(data)))
if err != nil {
return -1, err
}
return pid, nil
}
// Check if a app is running
func (d *Device) CheckAppRunning(appackage string) (bool, error) {
pid, err := d.GetAppPid(appackage)
if err != nil {
return false, err
}
if pid != -1 {
return true, nil
}
return false, nil
}
// Start a app using the package name
func (d *Device) StartApp(appackage string) error {
_, err := d.RunCommand(fmt.Sprintf("shell monkey -p %s -c android.intent.category.LAUNCHER 1", appackage))
return err
}
// Force kill a running app
func (d *Device) KillApp(appackage string) error {
_, err := d.RunCommand(fmt.Sprintf("shell am force-stop %s", appackage))
return err
}