Auto.js文档
综述
Q & A
如何定时运行脚本
定时任何如何获取外部参数
如何把图片和脚本一起打包,或者打包多个脚本
如何使打包的应用不显示主界面
Auto.js自带的模块和函数中没有的功能如何实现
关于本文档
API稳定性
如何阅读本文档
input([i, ]text)
images.detectsColor(image, color, x, y[, threshold
App
app.versionCode
app.versionName
app.autojs.versionCode
app.autojs.versionName
app.launchApp(appName)
app.launch(packageName)
app.launchPackage(packageName)
app.getPackageName(appName)
app.getAppName(packageName)
app.openAppSetting(packageName)
app.viewFile(path)
app.editFile(path)
app.uninstall(packageName)
app.openUrl(url)
app.sendEmail(options)
app.startActivity(name)
进阶: 意图Intent
app.intent(options)
app.startActivity(options)
app.sendBroadcast(options)
app.startService(options)
app.sendBroadcast(name)
app.intentToShell(options)
app.parseUri(uri)
app.getUriForFile(path)
全局变量与函数
sleep(n)
currentPackage()
currentActivity()
setClip(text)
getClip()
toast(message)
toastLog(message)
waitForActivity(activity[, period = 200])
waitForPackage(package[, period = 200])
exit()
random(min, max)
random()
requiresApi(api)
requiresAutojsVersion(version)
runtime.requestPermissions(permissions)
runtime.loadJar(path)
runtime.loadDex(path)
context
Console
console.show()
console.hide()
console.clear()
console.log([data][, ...args])
console.verbose([data][, ...args])
console.info([data][, ...args])
console.warn([data][, ...args])
console.error([data][, ...args])
console.assert(value, message)
console.time([label])
console.timeEnd(label)
console.trace([data][, ...args])
console.input(data[, ...args])
console.rawInput(data[, ...args])
console.setSize(w, h)
console.setPosition(x, y)
console.setGlobalLogConfig(config)
print(text)
基于坐标的触摸模拟
setScreenMetrics(width, height)
安卓7.0以上的触摸和手势模拟
click(x, y)
longClick(x, y)
press(x, y, duration)
swipe(x1, y1, x2, y2, duration)
gesture(duration, [x1, y1], [x2, y2], ...)
gestures([delay1, duration1, [x1, y1], [x2, y2], .
RootAutomator
RootAutomator.tap(x, y[, id])
RootAutomator.swipe(x1, x2, y1, y2[, duration, id]
RootAutomator.press(x, y, duration[, id])
RootAutomator.longPress(x, y[\, id])
RootAutomator.touchDown(x, y[, id])
RootAutomator.touchMove(x, y[, id])
RootAutomator.touchUp([id])
使用root权限点击和滑动的简单命令
Tap(x, y)
Swipe(x1, y1, x2, y2, [duration])
Device
device.width
device.height
device.buildId
device.broad
device.brand
device.device
deivce.model
device.product
device.bootloader
device.hardware
device.fingerprint
device.serial
device.sdkInt
device.incremental
device.release
device.baseOS
device.securityPatch
device.codename
device.getIMEI()
device.getAndroidId()
device.getMacAddress()
device.getBrightness()
device.getBrightnessMode()
device.setBrightness(b)
device.setBrightnessMode(mode)
device.getMusicVolume()
device.getNotificationVolume()
device.getAlarmVolume()
device.getMusicMaxVolume()
device.getNotificationMaxVolume()
device.getAlarmMaxVolume()
device.setMusicVolume(volume)
device.setNotificationVolume(volume)
device.setAlarmVolume(volume)
device.getBattery()
device.isCharging()
device.getTotalMem()
device.getAvailMem()
device.isScreenOn()
device.wakeUp()
device.wakeUpIfNeeded()
device.keepScreenOn([timeout])
device.keepScreenDim([timeout])
device.cancelKeepingAwake()
device.vibrate(millis)
device.cancelVibration()
Dialogs
dialogs.alert(title[, content, callback])
dialogs.confirm(title[, content, callback])
dialogs.rawInput(title[, prefill, callback])
dialogs.input(title[, prefill, callback])
dialogs.prompt(title[, prefill, callback])
dialogs.select(title, items, callback)
dialogs.singleChoice(title, items[, index, callbac
dialogs.multiChoice(title, items[, indices, callba
dialogs.build(properties)
Dialog
事件: show
事件: cancel
事件: dismiss
事件: positive
事件: negative
事件: neutral
事件: any
事件: item_select
事件: single_choice
事件: multi_choice
事件: input
事件: input_change
dialog.getProgress()
dialog.getMaxProgress()
dialog.getActionButton(action)
Engines
engines.execScript(name, script[, config])
engines.execScriptFile(path[, config])
engines.execAutoFile(path[, config])
engines.stopAll()
engines.stopAllAndToast()
engines.myEngine()
engines.all()
ScriptExecution
ScriptExecution.getEngine()
ScriptExecution.getConfig()
ScriptEngine
ScriptEngine.forceStop()
ScriptEngine.cwd()
ScriptEngine.getSource()
ScriptEngine.emit(eventName[, ...args])
ScriptConfig
delay
interval
loopTimes
getPath()
Events
events.emitter()
events.observeKey()
events.onKeyDown(keyName, listener)
events.onKeyUp(keyName, listener)
events.onceKeyDown(keyName, listener)
events.onceKeyUp(keyName, listener)
events.removeAllKeyDownListeners(keyName)
events.removeAllKeyUpListeners(keyName)
events.setKeyInterceptionEnabled([key, ]enabled)
events.observeTouch()
events.setTouchEventTimeout(timeout)
events.getTouchEventTimeout()
events.onTouch(listener)
events.removeAllTouchListeners()
事件: 'key'
事件: 'key_down'
事件: 'key_up'
事件: 'exit`
events.observeNotification()
events.observeToast()
事件: 'toast'
事件: 'notification'
Notification
Notification.number
Notification.when
Notification.getPackageName()
Notification.getTitle()
Notification.getText()
Notification.click()
Notification.delete()
KeyEvent
KeyEvent.getAction()
KeyEvent.getKeyCode()
KeyEvent.getEventTime()
KeyEvent.getDownTime()
KeyEvent.keyCodeToString(keyCode)
keys
EventEmitter
EventEmitter.defaultMaxListeners
EventEmitter.addListener(eventName, listener)
EventEmitter.emit(eventName[, ...args])
EventEmitter.eventNames()
EventEmitter.getMaxListeners()
EventEmitter.listenerCount(eventName)
EventEmitter.listeners(eventName)
EventEmitter.on(eventName, listener)
EventEmitter.once(eventName, listener)
EventEmitter.prependListener(eventName, listener)
EventEmitter.prependOnceListener(eventName, listen
EventEmitter.removeAllListeners([eventName])
EventEmitter.removeListener(eventName, listener)
EventEmitter.setMaxListeners(n)
events.broadcast: 脚本间广播
Floaty
floaty.window(layout)
floaty.rawWindow(layout)
floaty.closeAll()
FloatyWindow
window.setAdjustEnabled(enabled)
window.setPosition(x, y)
window.getX()
window.getY()
window.setSize(width, height)
window.getWidht()
window.getHeight()
window.close()
window.exitOnClose()
FloatyRawWindow
window.setTouchable(touchable)
window.setPosition(x, y)
window.getX()
window.getY()
window.setSize(width, height)
window.getWidht()
window.getHeight()
window.close()
window.exitOnClose()
Files
files.isFile(path)
files.isDir(path)
files.isEmptyDir(path)
files.join(parent, child)
files.create(path)
files.createWithDirs(path)
files.exists(path)
files.ensureDir(path)
files.read(path[, encoding = "utf-8"])
files.readBytes(path)
files.write(path, text[, encoding = "utf-8"])
files.writeBytes(path, bytes)
files.append(path, text[, encoding = 'utf-8'])
files.appendBytes(path, text[, encoding = 'utf-8']
files.copy(fromPath, toPath)
files.move(fromPath, toPath)
files.rename(path, newName)
files.renameWithoutExtension(path, newName)
files.getName(path)
files.getNameWithoutExtension(path)
files.getExtension(path)
files.remove(path)
files.removeDir(path)
files.getSdcardPath()
files.cwd()
files.path(relativePath)
files.listDir(path[, filter])
open(path[, mode = "r", encoding = "utf-8", buffer
ReadableTextFile
ReadableTextFile.read()
ReadableTextFile.read(maxCount)
ReadableTextFile.readline()
ReadableTextFile.readlines()
close()
PWritableTextFile
PWritableTextFile.write(text)
PWritableTextFile.writeline(line)
PWritableTextFile.writelines(lines)
PWritableTextFile.flush()
PWritableTextFile.close()
HTTP
http.get(url[, options, callback])
http.post(url, data[, options, callback])
http.postJson(url[, data, options, callback])
http.postMultipart(url, files[, options, callback]
http.request(url[, options, callback])
Response
Response.statusCode
Response.statusMessage
Response.headers
Response.body
Response.request
Response.url
Response.method
colors
colors.toString(color)
colors.red(color)
colors.green(color)
colors.blue(color)
colors.alpha(color)
colors.rgb(red, green, blue)
colors.argb(alpha, red, green, blue)
colors.parseColor(colorStr)
colors.isSimilar(color2, color2[, threshold, algor
colors.equals(color1, color2)
colors.BLACK
colors.DKGRAY
colors.GRAY
colors.LTGRAY
colors.WHITE
colors.RED
colors.GREEN
colors.BLUE
colors.YELLOW
colors.CYAN
colors.MAGENTA
colors.TRANSPARENT
Images
图片处理
images.read(path)
images.load(url)
images.copy(img)
images.save(image, path[, format = "png", quality
images.fromBase64(base64)
images.toBase64(img[, format = "png", quality = 10
images.fromBytes(bytes)
images.toBytes(img[, format = "png", quality = 100
images.clip(img, x, y, w, h)
images.resize(img, size[, interpolation])
images.scale(img, fx, fy[, interpolation])
images.rotate(img, degress[, x, y])
images.concat(img1, image2[, direction])
images.grayscale(img)
image.threshold(img, threshold, maxVal[, type])
images.adaptiveThreshold(img, maxValue, adaptiveMe
images.cvtColor(img, code[, dstCn])
images.inRange(img, lowerBound, upperBound)
images.interval(img, color, interval)
images.blur(img, size[, anchor, type])
images.medianBlur(img, size)
images.gaussianBlur(img, size[, sigmaX, sigmaY, ty
images.matToImage(mat)
找图找色
images.requestScreenCapture([landscape])
images.captureScreen()
images.captureScreen(path)
images.pixel(image, x, y)
images.findColor(image, color, options)
images.findColorInRegion(img, color, x, y[, width,
images.findColorEquals(img, color[, x, y, width, h
images.findMultiColors(img, firstColor, colors[, o
images.detectsColor(image, color, x, y[, threshold
images.findImage(img, template[, options])
images.findImageInRegion(img, template, x, y[, wid
images.matchTemplate(img, template, options)
MatchingResult
matches
points
first()
last()
leftmost()
topmost()
rightmost()
bottommost()
best()
worst()
sortBy(cmp)
Image
Image.getWidth()
Image.getHeight()
Image.saveTo(path)
Image.pixel(x, y)
Point
Point.x
Point.y
Canvas
canvas.drawARGB(a, r, g, b)
canvas.draw
Keys
back()
home()
powerDialog()
notifications()
quickSettings()
recents()
splitScreen()
Home()
Back()
Power()
Menu()
VolumeUp()
VolumeDown()
Camera()
Up()
Down()
Left()
Right()
OK()
Text(text)
KeyCode(code)
附录: KeyCode对照表
Media
media.scanFile(path)
media.playMusic(path[, volume, looping])
media.musicSeekTo(msec)
media.pauseMusic()
media.resumeMusic()
media.stopMusic()
media.isMusicPlaying()
media.getMusicDuration()
media.getMusicCurrentPosition()
module (模块)
基于控件的操作
auto([mode])
auto.waitFor()
auto.setMode(mode)
SimpleActionAutomator
click(text[, i])
click(left, top, bottom, right)
longClick(text[, i]))
scrollUp([i])
scrollDown([i])
setText([i, ]text)
input([i, ]text)
UiSelector
selector()
UiSelector.text(str)
UiSelector.textContains(str)
UiSelector.textStartsWith(prefix)
UiSelector.textEndsWith(suffix)
UiSelector.textMatches(reg)
UiSelector.desc(str)
UiSelector.descContains(str)
UiSelector.descStartsWith(prefix)
UiSelector.descEndsWith(suffix)
UiSelector.descMatches(reg)
UiSelector.id(resId)
UiSelector.idContains(str)
UiSelector.idStartsWith(prefix)
UiSelector.idEndsWith(suffix)
UiSelector.idMatches(reg)
UiSelector.className(str)
UiSelector.classNameContains(str)
UiSelector.classNameStartsWith(prefix)
UiSelector.classNameEndsWith(suffix)
UiSelector.classNameMatches(reg)
UiSelector.packageName(str)
UiSelector.packageNameContains(str)
UiSelector.packageNameStartsWith(prefix)
UiSelector.packageNameEndsWith(suffix)
UiSelector.packageNameMatches(reg)
UiSelector.bounds(left, top, right, buttom)
UiSelector.boundsInside(left, top, right, buttom)
UiSelector.boundsContains(left, top, right, buttom
UiSelector.drawingOrder(order)
UiSelector.clickable([b = true])
UiSelector.longClickable([b = true])
UiSelector.checkable([b = true])
UiSelector.selected([b = true])
UiSelector.enabled([b = true])
UiSelector.scrollable([b = true])
UiSelector.editable([b = true])
UiSelector.multiLine([b = true])
UiSelector.findOne()
UiSelector.findOne(timeout)
UiSelector.findOnce()
UiSelector.findOnce(i)
UiSelector.find()
UiSelector.untilFind()
UiSelector.exists()
UiSelector.waitFor()
UiSelector.filter(f)
UiObject
UiObject.click()
UiObject.longClick()
UiObject.setText(text)
UiObject.copy()
UiObject.cut()
UiObject.paste()
UiObject.setSelection(start, end)
UiObject.scrollForward()
UiObject.scrollBackward()
UiObject.select()
UiObject.collapse()
UiObject.expand()
UiObject.show()
UiObject.scrollUp()
UiObject.scrollDown()
UiObject.scrollLeft()
UiObject.scrollRight()
children()
childCount()
child(i)
parent()
bounds()
boundsInParent()
drawingOrder()
id()
text()
findByText(str)
findOne(selector)
find(selector)
UiCollection
UiCollection.size()
UiCollection.get(i)
UiCollection.each(func)
empty()
nonEmpty()
UiCollection.find(selector)
UiCollection.findOne(selector)
Rect
Rect.left
Rect.right
Rect.top
Rect.bottom
Rect.centerX()
Rect.centerY()
Rect.width()
Rect.height()
Rect.contains(r)
Rect.intersect(r)
UiSelector进阶
Sensors
sensors.register(sensorName[, delay])
sensors.unregister(emitter)
sensors.unregisterAll()
sensors.ignoresUnsupportedSensor
事件: 'unsupported_sensor'
SensorEventEmitter
事件: 'change'
事件: 'accuracy_change'
shell函数
shell(cmd[, root])
Shell
new Shell(root)
Shell.exec(cmd)
Shell.exit()
Shell.exitAndWaitFor()
Shell.setCallback(callback)
附录: shell命令简介
am命令
start [options] intent
startservice [options] intent
force-stop package
kill [options] package
kill-all
broadcast [options] intent
instrument [options] component
dumpheap [options] process file
monitor [options] 启动对崩溃或 ANR 的监控。
screen-compat {on|off} package
display-size [reset|widthxheight]
display-density dpi
to-uri intent
to-intent-uri intent
intent参数的规范
URI component package
应用包名
pm命令
list packages [options] filter
list permission-groups
list permissions [options] group
list instrumentation [options]
list features
list libraries
list users
path package
install [options] path
uninstall [options] package
clear package
enable package_or_component
disable package_or_component
disable-user [options] package_or_component
grant package_name permission
revoke package_name permission
set-install-location location
get-install-location
set-permission-enforced permission [true|false]
trim-caches desired_free_space
create-user user_name
remove-user user_id
get-max-users
其他命令
进行屏幕截图
列表文件
Threads
threads.start(action)
threads.shutDownAll()
threads.currentThread()
threads.disposable()
threads.atomic([initialValue])
threads.lock()
Thread
Thread.interrupt()
Thread.join([timeout])
isAlive()
waitFor()
Thread.setTimeout(callback, delay[, ...args])
Thread.setInterval(callback, delay[, ...args])
Thread.setImmediate(callback[, ...args])
Thread.clearInterval(id)
Thread.clearTimeout(id)
Thread.clearImmediate(id)
线程安全
sync(func)
线程通信
Timers
setInterval(callback, delay[, ...args])
setTimeout(callback, delay[, ...args])
setImmediate(callback[, ...args])
clearInterval(id)
clearTimeout(id)
clearImmediate(id)
用户界面: UI
视图: View
w
h
id
gravity
layout_gravity
margin
marginLeft
marginRight
marginTop
marginBottom
padding
paddingLeft
paddingRight
paddingTop
paddingBottom
bg
alpha
foreground
minHeight
minWidth
visbility
rotation
transformPivotX
transformPivotY
style
文本控件: text
text
textColor
textSize
textStyle
lines
maxLines
typeface
ellipsize
ems
autoLink
按钮控件: button
输入框控件: input
hint
textColorHint
textSizeHint
inputType
password
numeric
phoneNumber
digits
singleLine
图片控件: img
src
tint
scaleType
radius
radiusTopLeft
radiusTopRight
radiusBottomLeft
radiusBottomRight
borderWidth
borderColor
circle
垂直布局: vertical
layout_weight
水平布局: horizontal
layout_weight
线性布局: linear
帧布局: frame
相对布局: relative
勾选框控件: checkbox
选择框控件: radio
选择框布局: radiogroup
开关控件: switch
进度条控件: progressbar
拖动条控件: seekbar
下来菜单控件: spinner
时间选择控件: timepicker
日期选择控件: datepicker
浮动按钮控件: fab
标题栏控件: toolbar
卡片: card
抽屉布局: drawer
列表: list
Tab: tab
ui
ui.layout(xml)
ui.inflate(xml[, parent])
ui.findView(id)
ui.finish()
ui.setContentView(view)
ui.run(callback)
ui.post(callback[, daley])
ui.statusBarColor(color)
ui.showPopupMenu(view, menu)
尺寸的单位: Dimension
Drawables
颜色