driver

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 14, 2024 License: MIT Imports: 24 Imported by: 0

README

English | 简体中文

go-android-uiautomator

Android automation development using Go, so you need to learn some Go syntax before continuing.

This project references openatx/uiautomator2. The dump method actually uses u2.jar from the original project, and the input method is modified from senzhk/ADBKeyBoard. Here I list the libraries and projects used in this project. If there are any omissions, please contact me, and I will add them immediately with apologies.

  • GitHub tag (latest SemVer)
  • GitHub tag (latest SemVer)

Respect to the developers.

The project is still under development, so if you encounter any problems or bugs, please submit Issues. I will definitely see them as long as nothing unexpected happens ( •͈ᴗ⁃͈)ᓂ- - -♡

Also, the documentation demonstrates using Douyin v32.0.0 app. For features not covered in the documentation, please refer to the source code.

Preparation

  1. Prepare an Android phone

  2. Optional during development

    • Install Python, then install uiauto.dev via pip to view page structure

      pip install -U uiautodev
      
      uiauto.dev
      
    • Connect to computer and enable USB debugging

    • Use wireless debugging

[!NOTE]

For first-time use, star-ime input method will be automatically installed. If an installation prompt appears, please allow it.

Quick Start

go get github.com/shi-yunsheng/driver
import "github.com/shi-yunsheng/driver"

func main() {
    d := driver.New()
    
    d.Connect("192.168.10.128") // Check device serial number or IP via adb devices

	d.StartApp("com.ss.android.ugc.aweme") // Launch Douyin

	searchBtn, _ := d.WaitElement(driver.By{Selector: driver.ContentDesc, Value: "搜索"})
	if searchBtn != nil {
		searchBtn.Tap()
	}

	dy := "ismeSYS"
	msg := "Hello, Lao Shi"

	search, _ := d.WaitElement(driver.By{Selector: driver.ResourceID, Value: "com.ss.android.ugc.aweme:id/et_search_kw"})
	if search != nil {
		search.Input(dy)
		search.Search()
	}

	user, _ := d.WaitElement(driver.By{Selector: driver.EndsWithText, Value: fmt.Sprintf("抖音号:%s,按钮", dy)})
	if user != nil {
		user.Tap()
	}

	more, _ := d.WaitElement(driver.By{Selector: driver.ContentDesc, Value: "更多"})
	if more != nil {
		more.Tap()
	}

	sendBtn, _ := d.WaitElement(driver.By{Selector: driver.Text, Value: "发私信"})
	if sendBtn != nil {
		sendBtn.Tap()
	}

	message, _ := d.WaitElement(driver.By{Selector: driver.Text, Value: "发送消息"})
	if message != nil {
		message.Input(msg)
		message.Send()

		for i := 0; i < 5; i++ {
			d.Back()
		}
	}

	defer d.Cleanup()
}

API Document

New()

Create a driver to drive the entire automation work.

func main() {
   	d := driver.New()
}
Connect()

Used to connect to devices when developing and testing on PC. If using wired connection, the parameter is the corresponding serial number; if using wireless connection, the parameter can be the IP address.

[!NOTE]

If compiling to run on Android, this needs to be commented out or deleted~~~

d.Connect("192.168.10.128") // WLAN
// or USB d.Connect("22e3e987") 
Info()

Get device information.

deviceInfo := d.Info()
fmt.Println(deviceInfo)
StartApp()

Launch an application by passing the package name.

d.StartApp("com.ss.android.ugc.aweme") // Launch Douyin
StopApp()

Stop an application by passing the package name.

d.StopApp("com.ss.android.ugc.aweme")
RestartApp()

Restart an application by passing the package name.

d.RestartApp("com.ss.android.ugc.aweme")
InstallApp()

Install an application by passing the installation package path.

d.InstallApp("/data/local/tmp/douyin.apk")
UninstallApp()

Uninstall an application by passing the package name.

d.UninstallApp("com.ss.android.ugc.aweme")
Document()

Get the current page structure.

doc := d.Document()
fmt.Println(doc.RawXML)
FindElement()

Find a specific element node. If the node doesn't exist, returns nil. Currently only supports finding through xpath.

doc := d.Document()
search := doc.FindElement(`//node[@resource-id="com.ss.android.ugc.aweme:id/et_search_kw"]`)
if search != nil {
   	search.Input("老石话不多")
   	search.Search()
}
FindElements()

Similar to FindElement(), but FindElements() returns a group of element nodes.

doc := d.Document()
navbar := doc.FindElements(`//node[@resource-id="com.ss.android.ugc.aweme:id/0zg"]`)
for _, bar := range navbar {
   	fmt.Println(bar.Text())
}
WaitElement()

Wait for an element node to appear. Accepts a By type parameter containing selector type, value, and timeout duration (milliseconds). Returns nil and error if timeout occurs.

Supported selector types:

  • Text: Match by text content
  • ContentDesc: Match by content-desc attribute
  • Class: Match by class name
  • ResourceID: Match by resource ID
  • StartsWithText: Match by text prefix
  • EndsWithText: Match by text suffix
  • StartsWithContentDesc: Match by content-desc prefix
  • EndsWithContentDesc: Match by content-desc suffix
  • StartsWithClass: Match by class name prefix
  • EndsWithClass: Match by class name suffix
  • StartsWithResourceID: Match by resource ID prefix
  • EndsWithResourceID: Match by resource ID suffix
d := driver.New()

search, _ := d.WaitElement(driver.By{
   	Selector: driver.ResourceID,
   	Value: "com.ss.android.ugc.aweme:id/et_search_kw",
   })
   
if search != nil {
   	search.Input("老石话不多")
   	search.Search()
}
Text()

Get the text attribute value of an element node. Returns empty string "" if not found.

doc := d.Document()
likes := doc.FindElement(`//node[@resource-id="com.ss.android.ugc.aweme:id/ffl"]`)
if likes != nil {
   	fmt.Println(likes.Text())
}
ContentDesc()

Get the content-desc attribute value of an element node. Returns empty string "" if not found.

doc := d.Document()
likes := doc.FindElement(`//node[@resource-id="com.ss.android.ugc.aweme:id/ffl"]`)
if likes != nil {
   	fmt.Println(likes.ContentDesc())
}
GetBounds()

Get the bounds attribute value of an element node. Returns nil if not found.

doc := d.Document()
likes := doc.FindElement(`//node[@resource-id="com.ss.android.ugc.aweme:id/ffl"]`)
if likes != nil {
   	fmt.Println(likes.ContentDesc())
}
GetAttribute()

If there are other attributes not provided, you can use this method to get them.

doc := d.Document()
like := doc.FindElement(`//node[@resource-id="com.ss.android.ugc.aweme:id/ffl"]`)
if like != nil {
   	fmt.Println(likes.GetAttribute("resource-id"))
}
Tap()
  • driver Tap()

    Pass in coordinates (x,y) to tap at that location.

    d := driver.New()
    d.Tap(100, 200) // Tap at screen coordinates (100, 200)
    
  • element Tap()

    Directly tap the element.

    doc := d.Document()
    like := doc.FindElement(`//node[@resource-id="com.ss.android.ugc.aweme:id/ffl"]`)
    if likes != nil {
       	like.Tap() // Tap this element
    }
    

[!NOTE]

Coordinates are relative to the screen's top-left corner, and the coordinate range is x: [0, screen width], y: [0, screen height]

LongTap()
  • driver LongTap()

    Pass in coordinates (x,y) to long press at that location.

    d := driver.New()
    d.LongTap(400, 600) // Long press at screen coordinates (400, 600)
    
  • element LongTap()

    Directly long press the element.

    doc := d.Document()
    chat := doc.FindElement(`//node[@resource-id="com.ss.android.ugc.aweme:id/wvq"][@class="android.widget.Button"]`)
    if chat != nil {
       	chat.LongTap()
    }
    
Swipe()
  • driver Swipe()

    Swipe on the screen according to the input direction.

    d := driver.New()
    d.Swipe(driver.SWIPE_DOWN) // Swipe down
    
  • element Swipe()

    Swipe within the element's bounds according to the input direction.

    doc := d.Document()
    tabbar := doc.FindElement(`//node[@resource-id="com.ss.android.ugc.aweme:id/vf5"]`)
    if tabbar != nil {
    	tabbar.Swipe(driver.SWIPE_RIGHT) // Swipe right
    }
    
Input()
  • driver Input()

    Input text at the specified coordinates.

    d := driver.New()
    d.Input(400, 600, "老石")
    
  • element Input()

    If the element node is input-capable, directly input text into that element.

    d := driver.New()
    search, _ := d.WaitElement(driver.By{
       	Selector: driver.ResourceID,
       	Value: "com.ss.android.ugc.aweme:id/et_search_kw",
    })
    
    if search != nil {
       	search.Input("老石话不多")
       	search.Search()
    }
    
Screenshot()
  • driver Screenshot()

    Take a screenshot of the current screen.

    img := d.Screenshot()
    
  • element Screenshot()

    Take a screenshot of the node.

    d := driver.New()
    avatar, _ := d.WaitElement(driver.By{
       	Selector: driver.ResourceID,
       	Value: "com.ss.android.ugc.aweme:id/user_avatar",
    })
    
    if avatar != nil {
           avatar.Screenshot()
       }
    

[!CAUTION]

If the node is obscured, the screenshot will only show the unobscured parts.

Run()

Execute Android shell commands.

if ls, err := d.Run("ls"); err != nil {
    fmt.Println(ls)
}
Cleanup()

Cleanup operations, generally used when the program completes.

defer d.Cleanup()

Documentation

Index

Constants

View Source
const (
	TEMP_PATH        = "temp"
	ROOT_PATH        = "/data/local/tmp"
	IMAGE_PATH       = ROOT_PATH + "/screen.png"
	U2_URL           = "https://public.uiauto.devsleep.com/u2jar/0.1.5/u2.jar"
	U2_PATH          = ROOT_PATH + "/u2.jar"
	DAEMON_PATH      = ROOT_PATH + "/driver-daemon.log"
	ADB_KEYBOARD     = "com.android.starime/.StarIME"
	ADB_KEYBOARD_URL = "https://cf.ghproxy.cc/https://github.com/shi-yunsheng/star-ime/releases/download/v1.0.0/star-ime.apk"
	WAIT_TIMEOUT     = 10000
)
View Source
const (
	KEYCODE_UNKNOWN                       KeyCode = iota
	KEYCODE_SOFT_LEFT                             = 1
	KEYCODE_SOFT_RIGHT                            = 2
	KEYCODE_HOME                                  = 3
	KEYCODE_BACK                                  = 4
	KEYCODE_CALL                                  = 5
	KEYCODE_ENDCALL                               = 6
	KEYCODE_0                                     = 7
	KEYCODE_1                                     = 8
	KEYCODE_2                                     = 9
	KEYCODE_3                                     = 10
	KEYCODE_4                                     = 11
	KEYCODE_5                                     = 12
	KEYCODE_6                                     = 13
	KEYCODE_7                                     = 14
	KEYCODE_8                                     = 15
	KEYCODE_9                                     = 16
	KEYCODE_STAR                                  = 17
	KEYCODE_POUND                                 = 18
	KEYCODE_DPAD_UP                               = 19
	KEYCODE_DPAD_DOWN                             = 20
	KEYCODE_DPAD_LEFT                             = 21
	KEYCODE_DPAD_RIGHT                            = 22
	KEYCODE_DPAD_CENTER                           = 23
	KEYCODE_VOLUME_UP                             = 24
	KEYCODE_VOLUME_DOWN                           = 25
	KEYCODE_POWER                                 = 26
	KEYCODE_CAMERA                                = 27
	KEYCODE_CLEAR                                 = 28
	KEYCODE_A                                     = 29
	KEYCODE_B                                     = 30
	KEYCODE_C                                     = 31
	KEYCODE_D                                     = 32
	KEYCODE_E                                     = 33
	KEYCODE_F                                     = 34
	KEYCODE_G                                     = 35
	KEYCODE_H                                     = 36
	KEYCODE_I                                     = 37
	KEYCODE_J                                     = 38
	KEYCODE_K                                     = 39
	KEYCODE_L                                     = 40
	KEYCODE_M                                     = 41
	KEYCODE_N                                     = 42
	KEYCODE_O                                     = 43
	KEYCODE_P                                     = 44
	KEYCODE_Q                                     = 45
	KEYCODE_R                                     = 46
	KEYCODE_S                                     = 47
	KEYCODE_T                                     = 48
	KEYCODE_U                                     = 49
	KEYCODE_V                                     = 50
	KEYCODE_W                                     = 51
	KEYCODE_X                                     = 52
	KEYCODE_Y                                     = 53
	KEYCODE_Z                                     = 54
	KEYCODE_COMMA                                 = 55
	KEYCODE_PERIOD                                = 56
	KEYCODE_ALT_LEFT                              = 57
	KEYCODE_ALT_RIGHT                             = 58
	KEYCODE_SHIFT_LEFT                            = 59
	KEYCODE_SHIFT_RIGHT                           = 60
	KEYCODE_TAB                                   = 61
	KEYCODE_SPACE                                 = 62
	KEYCODE_SYM                                   = 63
	KEYCODE_EXPLORER                              = 64
	KEYCODE_ENVELOPE                              = 65
	KEYCODE_ENTER                                 = 66
	KEYCODE_DEL                                   = 67
	KEYCODE_GRAVE                                 = 68
	KEYCODE_MINUS                                 = 69
	KEYCODE_EQUALS                                = 70
	KEYCODE_LEFT_BRACKET                          = 71
	KEYCODE_RIGHT_BRACKET                         = 72
	KEYCODE_BACKSLASH                             = 73
	KEYCODE_SEMICOLON                             = 74
	KEYCODE_APOSTROPHE                            = 75
	KEYCODE_SLASH                                 = 76
	KEYCODE_AT                                    = 77
	KEYCODE_NUM                                   = 78
	KEYCODE_HEADSETHOOK                           = 79
	KEYCODE_FOCUS                                 = 80
	KEYCODE_PLUS                                  = 81
	KEYCODE_MENU                                  = 82
	KEYCODE_NOTIFICATION                          = 83
	KEYCODE_SEARCH                                = 84
	KEYCODE_MEDIA_PLAY_PAUSE                      = 85
	KEYCODE_MEDIA_STOP                            = 86
	KEYCODE_MEDIA_NEXT                            = 87
	KEYCODE_MEDIA_PREVIOUS                        = 88
	KEYCODE_MEDIA_REWIND                          = 89
	KEYCODE_MEDIA_FAST_FORWARD                    = 90
	KEYCODE_MUTE                                  = 91
	KEYCODE_PAGE_UP                               = 92
	KEYCODE_PAGE_DOWN                             = 93
	KEYCODE_PICTSYMBOLS                           = 94
	KEYCODE_SWITCH_CHARSET                        = 95
	KEYCODE_BUTTON_A                              = 96
	KEYCODE_BUTTON_B                              = 97
	KEYCODE_BUTTON_C                              = 98
	KEYCODE_BUTTON_X                              = 99
	KEYCODE_BUTTON_Y                              = 100
	KEYCODE_BUTTON_Z                              = 101
	KEYCODE_BUTTON_L1                             = 102
	KEYCODE_BUTTON_R1                             = 103
	KEYCODE_BUTTON_L2                             = 104
	KEYCODE_BUTTON_R2                             = 105
	KEYCODE_BUTTON_THUMBL                         = 106
	KEYCODE_BUTTON_THUMBR                         = 107
	KEYCODE_BUTTON_START                          = 108
	KEYCODE_BUTTON_SELECT                         = 109
	KEYCODE_BUTTON_MODE                           = 110
	KEYCODE_ESCAPE                                = 111
	KEYCODE_FORWARD_DEL                           = 112
	KEYCODE_CTRL_LEFT                             = 113
	KEYCODE_CTRL_RIGHT                            = 114
	KEYCODE_CAPS_LOCK                             = 115
	KEYCODE_SCROLL_LOCK                           = 116
	KEYCODE_META_LEFT                             = 117
	KEYCODE_META_RIGHT                            = 118
	KEYCODE_FUNCTION                              = 119
	KEYCODE_SYSRQ                                 = 120
	KEYCODE_BREAK                                 = 121
	KEYCODE_MOVE_HOME                             = 122
	KEYCODE_MOVE_END                              = 123
	KEYCODE_INSERT                                = 124
	KEYCODE_FORWARD                               = 125
	KEYCODE_MEDIA_PLAY                            = 126
	KEYCODE_MEDIA_PAUSE                           = 127
	KEYCODE_MEDIA_CLOSE                           = 128
	KEYCODE_MEDIA_EJECT                           = 129
	KEYCODE_MEDIA_RECORD                          = 130
	KEYCODE_F1                                    = 131
	KEYCODE_F2                                    = 132
	KEYCODE_F3                                    = 133
	KEYCODE_F4                                    = 134
	KEYCODE_F5                                    = 135
	KEYCODE_F6                                    = 136
	KEYCODE_F7                                    = 137
	KEYCODE_F8                                    = 138
	KEYCODE_F9                                    = 139
	KEYCODE_F10                                   = 140
	KEYCODE_F11                                   = 141
	KEYCODE_F12                                   = 142
	KEYCODE_NUM_LOCK                              = 143
	KEYCODE_NUMPAD_0                              = 144
	KEYCODE_NUMPAD_1                              = 145
	KEYCODE_NUMPAD_2                              = 146
	KEYCODE_NUMPAD_3                              = 147
	KEYCODE_NUMPAD_4                              = 148
	KEYCODE_NUMPAD_5                              = 149
	KEYCODE_NUMPAD_6                              = 150
	KEYCODE_NUMPAD_7                              = 151
	KEYCODE_NUMPAD_8                              = 152
	KEYCODE_NUMPAD_9                              = 153
	KEYCODE_NUMPAD_DIVIDE                         = 154
	KEYCODE_NUMPAD_MULTIPLY                       = 155
	KEYCODE_NUMPAD_SUBTRACT                       = 156
	KEYCODE_NUMPAD_ADD                            = 157
	KEYCODE_NUMPAD_DOT                            = 158
	KEYCODE_NUMPAD_COMMA                          = 159
	KEYCODE_NUMPAD_ENTER                          = 160
	KEYCODE_NUMPAD_EQUALS                         = 161
	KEYCODE_NUMPAD_LEFT_PAREN                     = 162
	KEYCODE_NUMPAD_RIGHT_PAREN                    = 163
	KEYCODE_VOLUME_MUTE                           = 164
	KEYCODE_INFO                                  = 165
	KEYCODE_CHANNEL_UP                            = 166
	KEYCODE_CHANNEL_DOWN                          = 167
	KEYCODE_ZOOM_IN                               = 168
	KEYCODE_ZOOM_OUT                              = 169
	KEYCODE_TV                                    = 170
	KEYCODE_WINDOW                                = 171
	KEYCODE_GUIDE                                 = 172
	KEYCODE_DVR                                   = 173
	KEYCODE_BOOKMARK                              = 174
	KEYCODE_CAPTIONS                              = 175
	KEYCODE_SETTINGS                              = 176
	KEYCODE_TV_POWER                              = 177
	KEYCODE_TV_INPUT                              = 178
	KEYCODE_STB_POWER                             = 179
	KEYCODE_STB_INPUT                             = 180
	KEYCODE_AVR_POWER                             = 181
	KEYCODE_AVR_INPUT                             = 182
	KEYCODE_PROG_RED                              = 183
	KEYCODE_PROG_GREEN                            = 184
	KEYCODE_PROG_YELLOW                           = 185
	KEYCODE_PROG_BLUE                             = 186
	KEYCODE_APP_SWITCH                            = 187
	KEYCODE_BUTTON_1                              = 188
	KEYCODE_BUTTON_2                              = 189
	KEYCODE_BUTTON_3                              = 190
	KEYCODE_BUTTON_4                              = 191
	KEYCODE_BUTTON_5                              = 192
	KEYCODE_BUTTON_6                              = 193
	KEYCODE_BUTTON_7                              = 194
	KEYCODE_BUTTON_8                              = 195
	KEYCODE_BUTTON_9                              = 196
	KEYCODE_BUTTON_10                             = 197
	KEYCODE_BUTTON_11                             = 198
	KEYCODE_BUTTON_12                             = 199
	KEYCODE_BUTTON_13                             = 200
	KEYCODE_BUTTON_14                             = 201
	KEYCODE_BUTTON_15                             = 202
	KEYCODE_BUTTON_16                             = 203
	KEYCODE_LANGUAGE_SWITCH                       = 204
	KEYCODE_MANNER_MODE                           = 205
	KEYCODE_3D_MODE                               = 206
	KEYCODE_CONTACTS                              = 207
	KEYCODE_CALENDAR                              = 208
	KEYCODE_MUSIC                                 = 209
	KEYCODE_CALCULATOR                            = 210
	KEYCODE_ZENKAKU_HANKAKU                       = 211
	KEYCODE_EISU                                  = 212
	KEYCODE_MUHENKAN                              = 213
	KEYCODE_HENKAN                                = 214
	KEYCODE_KATAKANA_HIRAGANA                     = 215
	KEYCODE_YEN                                   = 216
	KEYCODE_RO                                    = 217
	KEYCODE_KANA                                  = 218
	KEYCODE_ASSIST                                = 219
	KEYCODE_BRIGHTNESS_DOWN                       = 220
	KEYCODE_BRIGHTNESS_UP                         = 221
	KEYCODE_MEDIA_AUDIO_TRACK                     = 222
	KEYCODE_SLEEP                                 = 223
	KEYCODE_WAKEUP                                = 224
	KEYCODE_PAIRING                               = 225
	KEYCODE_MEDIA_TOP_MENU                        = 226
	KEYCODE_11                                    = 227
	KEYCODE_12                                    = 228
	KEYCODE_LAST_CHANNEL                          = 229
	KEYCODE_TV_DATA_SERVICE                       = 230
	KEYCODE_VOICE_ASSIST                          = 231
	KEYCODE_TV_RADIO_SERVICE                      = 232
	KEYCODE_TV_TELETEXT                           = 233
	KEYCODE_TV_NUMBER_ENTRY                       = 234
	KEYCODE_TV_TERRESTRIAL_ANALOG                 = 235
	KEYCODE_TV_TERRESTRIAL_DIGITAL                = 236
	KEYCODE_TV_SATELLITE                          = 237
	KEYCODE_TV_SATELLITE_BS                       = 238
	KEYCODE_TV_SATELLITE_CS                       = 239
	KEYCODE_TV_SATELLITE_SERVICE                  = 240
	KEYCODE_TV_NETWORK                            = 241
	KEYCODE_TV_ANTENNA_CABLE                      = 242
	KEYCODE_TV_INPUT_HDMI_1                       = 243
	KEYCODE_TV_INPUT_HDMI_2                       = 244
	KEYCODE_TV_INPUT_HDMI_3                       = 245
	KEYCODE_TV_INPUT_HDMI_4                       = 246
	KEYCODE_TV_INPUT_COMPOSITE_1                  = 247
	KEYCODE_TV_INPUT_COMPOSITE_2                  = 248
	KEYCODE_TV_INPUT_COMPONENT_1                  = 249
	KEYCODE_TV_INPUT_COMPONENT_2                  = 250
	KEYCODE_TV_INPUT_VGA_1                        = 251
	KEYCODE_TV_AUDIO_DESCRIPTION                  = 252
	KEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP           = 253
	KEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN         = 254
	KEYCODE_TV_ZOOM_MODE                          = 255
	KEYCODE_TV_CONTENTS_MENU                      = 256
	KEYCODE_TV_MEDIA_CONTEXT_MENU                 = 257
	KEYCODE_TV_TIMER_PROGRAMMING                  = 258
	KEYCODE_HELP                                  = 259
	KEYCODE_NAVIGATE_PREVIOUS                     = 260
	KEYCODE_NAVIGATE_NEXT                         = 261
	KEYCODE_NAVIGATE_IN                           = 262
	KEYCODE_NAVIGATE_OUT                          = 263
	KEYCODE_STEM_PRIMARY                          = 264
	KEYCODE_STEM_1                                = 265
	KEYCODE_STEM_2                                = 266
	KEYCODE_STEM_3                                = 267
	KEYCODE_DPAD_UP_LEFT                          = 268
	KEYCODE_DPAD_DOWN_LEFT                        = 269
	KEYCODE_DPAD_UP_RIGHT                         = 270
	KEYCODE_DPAD_DOWN_RIGHT                       = 271
	KEYCODE_MEDIA_SKIP_FORWARD                    = 272
	KEYCODE_MEDIA_SKIP_BACKWARD                   = 273
	KEYCODE_MEDIA_STEP_FORWARD                    = 274
	KEYCODE_MEDIA_STEP_BACKWARD                   = 275
	KEYCODE_SOFT_SLEEP                            = 276
	KEYCODE_CUT                                   = 277
	KEYCODE_COPY                                  = 278
	KEYCODE_PASTE                                 = 279
	KEYCODE_SYSTEM_NAVIGATION_UP                  = 280
	KEYCODE_SYSTEM_NAVIGATION_DOWN                = 281
	KEYCODE_SYSTEM_NAVIGATION_LEFT                = 282
	KEYCODE_SYSTEM_NAVIGATION_RIGHT               = 283
	KEYCODE_ALL_APPS                              = 284
	KEYCODE_REFRESH                               = 285
	KEYCODE_THUMBS_UP                             = 286
	KEYCODE_THUMBS_DOWN                           = 287
	KEYCODE_PROFILE_SWITCH                        = 288
	KEYCODE_VIDEO_APP_1                           = 289
	KEYCODE_VIDEO_APP_2                           = 290
	KEYCODE_VIDEO_APP_3                           = 291
	KEYCODE_VIDEO_APP_4                           = 292
	KEYCODE_VIDEO_APP_5                           = 293
	KEYCODE_VIDEO_APP_6                           = 294
	KEYCODE_VIDEO_APP_7                           = 295
	KEYCODE_VIDEO_APP_8                           = 296
	KEYCODE_FEATURED_APP_1                        = 297
	KEYCODE_FEATURED_APP_2                        = 298
	KEYCODE_FEATURED_APP_3                        = 299
	KEYCODE_FEATURED_APP_4                        = 300
	KEYCODE_DEMO_APP_1                            = 301
	KEYCODE_DEMO_APP_2                            = 302
	KEYCODE_DEMO_APP_3                            = 303
	KEYCODE_DEMO_APP_4                            = 304
)

Variables

View Source
var (
	ErrDeviceNotFound  = fmt.Errorf("device not found")
	ErrDeviceOffline   = fmt.Errorf("device offline")
	ErrMultipleDevices = fmt.Errorf("multiple devices found")
	ErrFileNotFound    = fmt.Errorf("file not found")
	ErrDownloadFailed  = fmt.Errorf("download failed")
	ErrSelectorEmpty   = fmt.Errorf("selector is empty")
	ErrElementNotFound = fmt.Errorf("element not found")
)

Functions

func CreateDir

func CreateDir(path string) bool

CreateDir creates a directory and all necessary parent directories Parameters:

  • path: Path of directory to create

Returns:

  • bool: true if successful, false otherwise

func CropImage

func CropImage(img image.Image, cropRect image.Rectangle) image.Image

CropImage crops a portion of the source image based on the specified rectangle. Parameters:

  • img: The source image to crop from
  • cropRect: Rectangle defining the crop boundaries

Returns:

  • The cropped image

func Daemon

func Daemon(exec func())

Daemon runs the provided function as a daemon process Parameters:

  • exec: The function to run in the daemon process

func DeleteAll

func DeleteAll(path string) bool

DeleteAll recursively deletes a file or directory Parameters:

  • path: Path to delete

Returns:

  • bool: true if successful, false otherwise

func DirExists

func DirExists(path string) bool

DirExists checks if a directory exists at the specified path Parameters:

  • path: Path to check

Returns:

  • bool: true if directory exists, false otherwise

func FileExists

func FileExists(path string) bool

FileExists checks if a file exists at the specified path Parameters:

  • path: Path to check

Returns:

  • bool: true if file exists, false otherwise

func GetRandomFloatInRange

func GetRandomFloatInRange(min, max float32) float32

GetRandomFloatInRange returns a random floating-point number between the specified min and max values (inclusive). Parameters:

  • min: The minimum value of the range.
  • max: The maximum value of the range.

Returns:

  • A random float32 between min (inclusive) and max (exclusive).

func GetRandomIntInRange

func GetRandomIntInRange(min, max int) int

GetRandomIntInRange returns a random integer between the specified min and max values (inclusive). Parameters:

  • min: The minimum value of the range.
  • max: The maximum value of the range.

Returns:

  • A random integer between min (inclusive) and max (exclusive).

func Image2Base64

func Image2Base64(img image.Image) (string, error)

Image2Base64 converts an image to a base64 encoded string. Parameters:

  • img: The image to convert

Returns:

  • The base64 encoded string and any error encountered

func LoadImage

func LoadImage(path string) (image.Image, error)

LoadImage loads an image from the specified file path. Parameters:

  • path: Path to the image file

Returns:

  • The loaded image and any error encountered

func Request

func Request(opt *Requester) (map[string]any, error)

Request sends an HTTP request based on the provided Requester options. Parameters:

  • opt: A pointer to a Requester struct containing request details.

Returns:

  • map[string]any: A map containing the response data if successful.
  • error: An error object if the request fails.

Types

type Bounds

type Bounds struct {
	LTX int // Left-Top X coordinate
	LTY int // Left-Top Y coordinate
	RBX int // Right-Bottom X coordinate
	RBY int // Right-Bottom Y coordinate
}

Bounds represents the coordinates of a UI element's bounding box

func FindImage added in v1.0.1

func FindImage(sourceImage image.Image, targetImage image.Image) (*Bounds, error)

TODO: Implement FindImage

type By

type By struct {
	Selector Selector
	Value    string
	Timeout  int
}

By represents a selector and its value

type Direction

type Direction int
const (
	SWIPE_UP Direction = iota
	SWIPE_DOWN
	SWIPE_LEFT
	SWIPE_RIGHT
)

type Driver added in v1.0.1

type Driver struct {
	// contains filtered or unexported fields
}

Driver represents the core structure for Android UI automation

func New

func New() *Driver

New creates and initializes a new driver instance Returns:

  • *Driver: Configured driver object ready for automation

func (*Driver) Back added in v1.0.1

func (d *Driver) Back() bool

Back simulates pressing the back button Returns:

  • bool: true if successful, false otherwise

func (*Driver) Battery added in v1.0.1

func (d *Driver) Battery() int

Battery retrieves the current battery level of the device Returns:

  • An integer representing the battery level (0-100)
  • If the battery level cannot be retrieved, it returns 0

func (*Driver) Cleanup added in v1.0.1

func (d *Driver) Cleanup()

Cleanup performs cleanup after the driver:

  • Stopping UiAutomator service
  • Restoring default keyboard

func (*Driver) Clear added in v1.0.1

func (d *Driver) Clear(x, y int)

Clear clears the text at the given coordinates Parameters:

  • x: The x-coordinate to clear
  • y: The y-coordinate to clear

func (*Driver) Connect added in v1.0.1

func (d *Driver) Connect(device string) error

Connect establishes a connection to an Android device Parameters:

  • device: device serial number or identifier

Returns:

  • error: nil if successful, otherwise:
  • ErrMultipleDevices if multiple devices are connected
  • ErrDeviceOffline if the device is offline
  • Other errors from adb command execution

func (*Driver) CopyFile added in v1.0.1

func (d *Driver) CopyFile(src, dest string) bool

CopyFile copies a file from one path to another Parameters:

  • src: Source path of file to copy
  • dest: Destination path of file to copy

Returns:

  • bool: true if successful, false otherwise

func (*Driver) CreateDir added in v1.0.1

func (d *Driver) CreateDir(path string) bool

CreateDir creates a directory and any necessary parent directories Parameters:

  • path: Path where to create directory

Returns:

  • bool: true if successful, false otherwise

func (*Driver) CreateFile added in v1.0.1

func (d *Driver) CreateFile(text, path string) bool

CreateFile creates a new file with the given text content Parameters:

  • text: Content to write to file
  • path: Path where to create file

Returns:

  • bool: true if successful, false otherwise

func (*Driver) DeleteFile added in v1.0.1

func (d *Driver) DeleteFile(path string) bool

DeleteFile deletes a file or directory recursively Parameters:

  • path: Path to delete

Returns:

  • bool: true if successful, false otherwise

func (*Driver) DirExists added in v1.0.1

func (d *Driver) DirExists(path string) bool

DirExists checks if a directory exists at the given path Parameters:

  • path: Path to check

Returns:

  • bool: true if directory exists, false otherwise

func (*Driver) Document added in v1.0.1

func (d *Driver) Document() *document

Document retrieves and parses the UI hierarchy of the current screen. It executes a UI dump command and parses the resulting XML.

Returns:

  • *document: The parsed UI document structure
  • nil: If unable to get UI dump or parse the XML

func (*Driver) DownloadFile added in v1.0.1

func (d *Driver) DownloadFile(url string, filepath string) error

DownloadFile downloads a file from the specified URL and saves it to the given path. For non-Android systems, it first downloads to a temporary location and then pushes to device. Parameters:

  • url: The URL of the file to download
  • filepath: The destination path where the file should be saved

Returns:

  • error: nil if successful, otherwise contains error details

func (*Driver) Enter added in v1.0.1

func (d *Driver) Enter() bool

Enter simulates pressing the enter key Returns:

  • bool: true if successful, false otherwise

func (*Driver) FileExists added in v1.0.1

func (d *Driver) FileExists(path string) bool

FileExists checks if a file exists at the given path Parameters:

  • path: Path to check

Returns:

  • bool: true if file exists, false otherwise

func (*Driver) GetIMEI added in v1.0.1

func (d *Driver) GetIMEI() string

GetIMEI retrieves the IMEI (International Mobile Equipment Identity) of the device. The method varies based on Android version - uses getprop for Android 12+ and service call for earlier versions. Returns:

  • string: Device IMEI if found, empty string if not found

func (*Driver) GetIP added in v1.0.1

func (d *Driver) GetIP() string

GetIP retrieves the IP address of the device's WLAN interface. Returns:

  • string: IP address if found, "localhost" if not found, "unknown" on error

func (*Driver) GetResolution added in v1.0.1

func (d *Driver) GetResolution() (int, int)

GetResolution retrieves the screen resolution of the device. Returns:

  • int: Screen width in pixels
  • int: Screen height in pixels

func (*Driver) Home added in v1.0.1

func (d *Driver) Home() bool

Home simulates pressing the home button Returns:

  • bool: true if successful, false otherwise

func (*Driver) Info added in v1.0.1

func (d *Driver) Info() string

Info retrieves device information and returns it as a JSON string. The information includes device model, brand, Android version, screen size, etc. Returns:

  • string: JSON formatted device information

func (*Driver) Input added in v1.0.1

func (d *Driver) Input(x, y int, text string)

Input types the specified text at the given coordinates Parameters:

  • x: The x-coordinate to tap
  • y: The y-coordinate to tap
  • text: The text to input

func (*Driver) InstallApp added in v1.0.1

func (d *Driver) InstallApp(app string, isDel bool)

InstallApp installs an APK file on the Android device Parameters:

  • app: path to the APK file to install
  • isDel: whether to delete the APK file after installation

func (*Driver) KeyEvent added in v1.0.1

func (d *Driver) KeyEvent(keyCode KeyCode) bool

KeyEvent sends a key event with the specified keycode Parameters:

  • keyCode: The Android key code to send

Returns:

  • bool: true if successful, false otherwise

func (*Driver) LoadImage added in v1.0.1

func (d *Driver) LoadImage(path string) (image.Image, error)

LoadImage loads an image from the device or local filesystem. For non-Android systems, pulls the image from device first. Parameters:

  • path: Path to the image file

Returns:

  • The loaded image and any error encountered

func (*Driver) LongTap added in v1.0.1

func (d *Driver) LongTap(x, y int)

LongTap performs a long tap action at the specified coordinates. Parameters:

  • x: The x-coordinate to long tap.
  • y: The y-coordinate to long tap.

func (*Driver) MemoryInfo added in v1.0.1

func (d *Driver) MemoryInfo() string

MemoryInfo retrieves memory information of the device. Returns:

  • string: Raw memory information output from dumpsys meminfo

func (*Driver) Menu added in v1.0.1

func (d *Driver) Menu() bool

Menu simulates pressing the menu button Returns:

  • bool: true if successful, false otherwise

func (*Driver) MoveFile added in v1.0.1

func (d *Driver) MoveFile(src, dest string) bool

MoveFile moves a file from one path to another Parameters:

  • src: Source path of file to move
  • dest: Destination path of file to move

Returns:

  • bool: true if successful, false otherwise

func (*Driver) Power added in v1.0.1

func (d *Driver) Power() bool

Power simulates pressing the power button Returns:

  • bool: true if successful, false otherwise

func (*Driver) PowerOff added in v1.0.1

func (d *Driver) PowerOff()

PowerOff simulates powering off the device This will shut down the entire device

func (*Driver) ReadFile added in v1.0.1

func (d *Driver) ReadFile(path string) (string, error)

ReadFile reads the content of a file Parameters:

  • path: Path of file to read

Returns:

  • string: Content of the file
  • error: nil if successful, otherwise error details

func (*Driver) Reboot added in v1.0.1

func (d *Driver) Reboot()

Reboot simulates a device reboot command This will restart the entire device

func (*Driver) RestartApp added in v1.0.1

func (d *Driver) RestartApp(app string)

RestartApp restarts an Android application by stopping and starting it Parameters:

  • app: full package name of the application to restart

func (*Driver) Run added in v1.0.1

func (d *Driver) Run(cmd string, args ...string) (string, error)

Run executes an adb command. Parameters:

  • cmd: The command to execute.
  • args: Additional arguments for the command.

Returns:

  • string: The output of the command.
  • error: An error object if the command execution fails.

func (*Driver) SaveImage added in v1.0.1

func (d *Driver) SaveImage(img image.Image, path string) error

SaveImage saves an image to the specified file path in PNG format. Parameters:

  • img: The image to save
  • path: Path where the image will be saved

Returns:

  • Any error encountered during saving

func (*Driver) Screenshot added in v1.0.1

func (d *Driver) Screenshot() image.Image

Screenshot captures the current screen of the device. Deletes any existing screenshot file before capturing.

Returns:

  • The captured screenshot as an image

func (*Driver) ScreenshotBase64 added in v1.0.1

func (d *Driver) ScreenshotBase64() (string, error)

ScreenshotBase64 captures the current screen and returns it as a base64 encoded string. It first takes a screenshot using Screenshot() and then converts it to base64 format.

Returns:

  • string: The base64 encoded screenshot image
  • error: Any error that occurred during the process

func (*Driver) Search added in v1.0.1

func (d *Driver) Search() bool

Search simulates pressing the search button Returns:

  • bool: true if successful, false otherwise

func (*Driver) StartApp added in v1.0.1

func (d *Driver) StartApp(app string) bool

StartApp launches an Android application using its package name Parameters:

  • app: full package name of the application (e.g. "com.example.app/.MainActivity")

Returns:

  • bool: true if app successfully started within timeout, false otherwise

func (*Driver) StartCharging added in v1.0.1

func (d *Driver) StartCharging()

StartCharging resets the battery system, enabling charging again This restores all charging sources and allows the device to charge

func (*Driver) StopApp added in v1.0.1

func (d *Driver) StopApp(app string)

StopApp forcefully stops a running Android application Parameters:

  • app: package name of the application to stop

func (*Driver) StopCharging added in v1.0.1

func (d *Driver) StopCharging()

StopCharging disables all charging sources (AC, USB, Wireless) This will prevent the device from charging

func (*Driver) StorageInfo added in v1.0.1

func (d *Driver) StorageInfo() string

StorageInfo retrieves storage usage information of the device's SD card. Returns:

  • string: Storage usage percentage of /sdcard partition

func (*Driver) Swipe added in v1.0.1

func (d *Driver) Swipe(direction Direction)

Swipe performs a swipe gesture across the entire screen Parameters:

  • direction: swipe direction, one of SWIPE_UP/SWIPE_DOWN/SWIPE_LEFT/SWIPE_RIGHT

func (*Driver) SwitchAdbKeyboard added in v1.0.1

func (d *Driver) SwitchAdbKeyboard() bool

SwitchAdbKeyboard switches the keyboard input method to the ADB keyboard Returns:

  • bool: true if the switch was successful, false otherwise

func (*Driver) SwitchDefaultKeyboard added in v1.0.1

func (d *Driver) SwitchDefaultKeyboard() bool

SwitchDefaultKeyboard switches the keyboard input method to the default keyboard Returns:

  • bool: true if the switch was successful, false otherwise

func (*Driver) Tap added in v1.0.1

func (d *Driver) Tap(x, y int)

Tap performs a tap action at the specified coordinates. Parameters:

  • x: The x-coordinate to tap.
  • y: The y-coordinate to tap.

func (*Driver) UninstallApp added in v1.0.1

func (d *Driver) UninstallApp(app string)

UninstallApp uninstalls an installed Android application Parameters:

  • app: package name of the application to uninstall

func (*Driver) VolumeDown added in v1.0.1

func (d *Driver) VolumeDown() bool

VolumeDown simulates pressing the volume down button Returns:

  • bool: true if successful, false otherwise

func (*Driver) VolumeUp added in v1.0.1

func (d *Driver) VolumeUp() bool

VolumeUp simulates pressing the volume up button Returns:

  • bool: true if successful, false otherwise

func (*Driver) WaitElement added in v1.0.1

func (d *Driver) WaitElement(by By) (*element, error)

WaitElement waits for an element to appear on the screen and returns it. It polls periodically until the element is found or timeout is reached.

Parameters:

  • by: Selector configuration containing the search criteria and timeout

Returns:

  • *element: The found UI element, or nil if not found within timeout
  • error: ErrSelectorEmpty if selector is empty, ErrElementNotFound if element not found

type EditorAction

type EditorAction int
const (
	IME_ACTION_UNSPECIFIED EditorAction = iota
	IME_ACTION_NONE
	IME_ACTION_GO
	IME_ACTION_SEARCH
	IME_ACTION_SEND
	IME_ACTION_NEXT
	IME_ACTION_DONE
	IME_ACTION_PREVIOUS
)

type KeyCode

type KeyCode int

type Requester

type Requester struct {
	Url     string            // The URL to send the request to.
	Method  string            // The HTTP method to use (e.g., GET, POST).
	Headers map[string]string // A map of headers to include in the request.
	Data    interface{}       // The data to send with the request, if any.
}

Requester defines the structure for an HTTP request.

type Selector

type Selector string

Selector represents a selector type

const (
	Text                  Selector = "text"
	ContentDesc           Selector = "content-desc"
	Class                 Selector = "class"
	ResourceID            Selector = "resource-id"
	StartsWithText        Selector = "starts-with-text"
	EndsWithText          Selector = "ends-with-text"
	StartsWithContentDesc Selector = "starts-with-content-desc"
	EndsWithContentDesc   Selector = "ends-with-content-desc"
	StartsWithClass       Selector = "starts-with-class"
	EndsWithClass         Selector = "ends-with-class"
	StartsWithResourceID  Selector = "starts-with-resource-id"
	EndsWithResourceID    Selector = "ends-with-resource-id"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL