Auto.js 中文文档:https://hyb1996.github.io/AutoJs-Docs/#/?id=综述
pro 版本支持 Node.js
AutoJs Pro 7.0.4-1 实战教程—Most complete history well quickly、抖音极速版
- :https://blog.csdn.net/zy0412326/article/details/107180887/
- :https://blog.csdn.net/zy0412326/article/details/107190828
示例:
- AutoJs 4.1.0 实战教程—终极福利Apk:https://blog.csdn.net/zy0412326/article/details/105120435
- 自动化篇 | 使用 AutoJS Automatically receive Jingdou:https://www.bianchengquan.com/article/589931.html
- 2021 Autojs Dozens of small game and the most complete tech-oriented reading collection (含源码):Scripts make money:https://blog.csdn.net/qq_29117491/article/details/118634537
- The latest popular scriptAutojs源码分享:https://www.jb51.net/article/212542.htm
关键字:类似 autojs、autojs 综合实战
- 比 autojs 更强大、More simple one-stop auxiliary solution「Android智能辅助平台」:https://aznfz.com/document/sample
- 开维控制精灵Ctrl.js (类似auto.jsThe script development platform ):http://www.feiyunjs.com/2266.html
资料:
- autojs A similar script development tools,EasyClick和Auto.js有什么区别?:http://www.feiyunjs.com/2456.html
- Auto.js Quick start practice teaching:https://github.com/ErazerControl/2019double11
- Auto.js 从入门到精通( 95集 ):https://www.bilibili.com/video/BV1pQ4y1R7Us
- Auto.js(基础、速成、初中、高阶、终极、实战)
:https://www.songma.com/product/view338899.html【autojs】Intermediate advanced tutorial:https://www.bilibili.com/video/BV1eg411L7DD
auto.js The android game script( 37集 ):https://www.bilibili.com/video/BV1Po4y1Q7bE
- autojs 入门视频( 23集 ):https://www.bilibili.com/video/BV1g5411L7G6
- B站搜索的 autojs :https://search.bilibili.com/all?keyword=autojs
Autojs 从入门到放弃(AcFun 视频)
- :https://www.acfun.cn/v/ac17943282
- :https://zhuanlan.zhihu.com/p/156660560
AutoJS4.1.0实战教程:https://blog.csdn.net/zy0412326/article/details/104767602/
:https://blog.csdn.net/zy0412326/article/details/105710886/
autojs 之权限大全
:autojs之权限大全 – 知乎
1、前言
Auto.js Is a support barrier-free service Android 平台上的 JavaScript IDE.Autojs Is mainly based on the android barrier-free service,Automated control and monitoring mobile information processing.
根据官方文档定义:Auto.js 是一款无需 root 权限的 JavaScript 自动化软件.如何理解它?
- Auto.js 是一款安卓手机应用,和微信一样,安装在手机上使用
- Auto.js 是一款自动化软件,根据脚本内容便可以自动地执行相关的操作,并且手机无需root
- Auto.js 的脚本需要使用JavaScript编写
特性:
- 由无障碍服务实现的简单易用的自动操作函数
- 悬浮窗录制和运行
- 更专业&强大的选择器 API,提供对屏幕上的控件的寻找、遍历、获取信息、操作等.类似于 Google 的 UI 测试框架 UiAutomator,您也可以把他当做移动版UI测试框架使用
- 采用 JavaScript 为脚本语言,并支持代码补全、变量重命名、代码格式化、查找替换等功能,可以作为一个 JavaScript IDE 使用
- 支持使用 e4x 编写界面,并可以将 JavaScript 打包为 apk 文件,您可以用它来开发小工具应用
- 支持使用 Root 权限以提供更强大的屏幕点击、滑动、录制功能和运行 shell 命令.录制录制可产生js文件或二进制文件,录制动作的回放比较流畅
- 提供截取屏幕、保存截图、图片找色、找图等函数
- 可作为 Tasker 插件使用,结合 Tasker 可胜任日常工作流
- 带有界面分析工具,类似 Android Studio 的 LayoutInspector,可以分析界面层次和范围、获取界面上的控件信息
app: 应用.启动应用,卸载应用,使用应用查看、编辑文件、访问网页,发送应用间广播等.console: 控制台.记录运行的日志、错误、信息等.device: 设备.获取设备屏幕宽高、系统版本等信息,控制设备音量、亮度等.engines: 脚本引擎.用于启动其他脚本.events: 事件与监听.按键监听,通知监听,触摸监听等.floaty: 悬浮窗.用于显示自定义的悬浮窗.files: 文件系统.文件创建、获取信息、读写.http: HTTP.发送HTTP请求,例如GET, POST等.images, colors: 图片和图色处理.截图,剪切图片,找图找色,读取保存图片等.keys: 按键模拟.比如音量键、Home键模拟等.shell: Shell命令.threads: 多线程支持.ui: UI界面.用于显示自定义的UI界面,和用户交互.
除此之外,Auto.js内置了对Promise.
2、安装
各个版本区别:
- 4.1.1 版本:The free version of the final version,可以在所有 app 上进行操作
- 7.0. 版本:收费版,已经停售,
- 8.0 pro 版本:Block out some big platform,例如:微信、支付宝、抖音 等…
- Three versions feature difference is not that great, Mainly in some packing details,Functions optimization,bugFix some differences such as,其他没啥区别,4.1.1 Version can completely meet the demand of almost all…
The free version has been updated to 4.1.1 And no longer update,在网上搜索 autojs.apk 下载安装即可.Auto.js 因某种原因全网下架(黑灰产) .可以从 github 上下载源码编译安装.github 地址:https://github.com/hyb1996/Auto.js
- Auto.js 下载地址:https://www.lanzoui.com/b03h4tvwh
- Auto.js Pro 7.0.4-1:http://www.feiyunjs.com/1785.html
The latest version has already started to charge,下载地址:Auto.js Pro
- 手机安装 Auto.js 应用
- Open the phone barrier-free service,The purpose is to let the script can perform.
- 开启悬浮框(为了查看控件信息)
- Computer has a code editor,vscode最佳(Auto.js作者提供了vscodePlugin for debugging)
接下来需要写脚本了,可以
- 在vscode上写脚本,写好后发给手机,在Auto.js应用中加载运行
- 在vscode上写脚本,电脑与手机在同一局域网,通过安装auto.js的vscode插件(https://github.com/hyb1996/Auto.js-VSCode-Extension ),实现在vscode上运行,手机就会相应执行脚本
- 在手机的 Auto.js 应用中直接码代码(不提倡)
3、示例:Get the taobao meow c
1. 打开淘宝 —> Click on the collar meow COINS button
In order to write the script is simple,Taobao shop open meow in advance home page
auto.waitFor()var appName = "手机淘宝";launchApp(appName);sleep(3000);//Looking for led meow COINS button and click onvar lingmiaobi = text("领喵币").findOnce();if (lingmiaobi) {lingmiaobi.click();sleep(1000);}else {toast("Check to receiving no meow COINS button");//中止脚本exit();}
详解:
- Auto.js无需root,But need to open the application barrier-free mode,To open screen click after the otherauto.waitFor()Said to check the application after open accessibility to execute the following code,Otherwise have been stuck in here,Generally in the first line of the script
- launchApp()Can open the corresponding application,Due to different mobile phone response speed,This code to make it sleep3s.
- Positioning component isautojsOne of the most common operation,This is very similar to the front positiondom元素.Before any click all need to find the corresponding component,This is different from click a pixel location,Click on the component more can fit different resolution cell phone.在auto.jsSelected through a variety of conditions to control calledUiSelector(https://hyb1996.github.io/AutoJs-Docs/#/widgetsBasedAutomation?id=uiselector ).Then the filter condition is how to determine the?打开Auto.jsApplication of suspended window,In the meow shop home page,点击Auto.js悬浮窗After the choice of蓝色按钮,点击布局范围分析After select led meow COINS button查看控件信息,You can see the figure2所示的信息.
- click() Said click the element.
- toast() According to display a message box.
2. Click to enter the store/去浏览
//开始执行任务execTask();function execTask() {while(true) {var target = text("去进店").findOnce() || text("去浏览").findOnce();if (target == null) {toast("任务完成");break;}target.click();sleep(3000);//浏览网页20sviewWeb(20);back();sleep(1000);}}
viewWeb Is a function of one would want to write,The purpose is to simulate web browsing20s的操作,Although taobao requirements15s就行了,But may be partially mobile loading time consuming more,So write more5s.When judgment task bar”去进店”、”去浏览”的组件时,Click to jump to browse the AD,浏览完毕后,Return to the task bar page,Cycle do this until I couldn’t find”去进店”、”去浏览”component ends(After the completion of the task button text will become”已完成”).
3. 浏览广告
function viewWeb(time) {gesture(1000, [300, 600], [300, 300]);var cnt = 1;while(true) {var finish = desc("任务完成").exists() || textStartsWith("已获得").exists();if (finish || cnt > time) {break;}sleep(1000);cnt += 1;}//模拟返回键,Return to the task bar pageback();}
The parameters of the function maximum retention time for the current page(To prevent accidental and stuck to the page).
Browse the advertising done sign:
- The current page”任务完成”或”已获得*****”的组件
- In the current page time is greater than the maximum limit set by
gesture Refers to the screen sliding operation,This is the only involves the screen pixel statement.gesture(duration, [x1, y1], [x2, y2]表示用duration的时间,从(x1,y1)点滑到(x2,y2)点,In the code as shown in figure represented by1sSliding into a red dot from the yellow point,Smooth operation view advertising on reason is.
The activities of the taobao started sliding a,After waiting time can be enough,It didn’t extra code in the sliding.After browsing advertisingback()To simulate the return key to return to value the taskbar page.
This code positioning components used todesc(),for usedescBecause of the controldesc信息是”任务完成”,Remember how to view controls information?总之,Want to locate controls,First check it controls information.
4. 测试
The code is finally finished,The script to phone,在Auto.jsApplication click on the lower right corner+号,选择导入,In file orders, looking for the corresponding script loading.
Open the taobao shop to meow home page,返回 Auto.js,Click run to execute the script,In the log can see the scripts run log,I haven’t mentioned the log?In the script you can use log() 函数记录日志,这等同于 print,Often used for debugging or logging information.
5. 打包成apk
编写完代码,The code into a separate apk.
- 右下角+号,新建文件夹命名为 double11
- 在 double11 Folder loading corresponding script
- 如图选择,打包 apk
6. 选择、定位
1. The selector filter condition:除使用 text、desc Screening selector outside,Components of most attributes can be filtered,详情见官方文档.Single filter condition is often unable to locate the elements,So can make chain call.Such as positioning the closing of the task bar×按钮:
className("android.widget.Button").depth(18).indexInParent(1).findOnce();
2.定位选择器:findOnce() Said to find the first meet the conditions of control,找不到返回null;另外还有findOne(),findOne(time)等方法,具体的可以看文档.这里有一个坑,findOne()If no match is found in the component would have been looking for,直至所描述的控件出现为止,Therefore, this function will not returnnull,Can’t find may get stuck here,所以谨慎使用.
3.click():When the positioning of the elements of theclickable属性为true时,才可以点击,If you see a certain controlclickable为false,It shows that this control cannot point!!May be you want to click it child/父控件.
源码参考https://github.com/ErazerControl/2019double11,切换 tag 至 v1.0.0
7. 示例:Scroll through friends
示例代码:
function print_lian_xi_ren(){/* 找控件 */log(text("通讯录").findOne().parent().parent());/* When it finds the control 的 "点击属性" 是 false 时,May be this control itself is nested in another control,The outer control is the inner control of the parent control,Check to see if the parent can click,如果父控件 的 "点击属性" 仍然是 false 时,Continue to find the parent,直到找到 "点击属性" 是 true 时,即可 点击*/var btn_txl = text("通讯录").findOne().parent().parent();btn_txl.click();sleep(1000)/* 打印联系人 */var lxr = id("com.tencent.mm:id/ft6").find()lxr.forEach(element => {people_name = element.text();log(people_name);click(people_name);sleep(1000);back();sleep(1000);});}function cha_kan_peng_you_quan(){/* 控件坐标 */var bounds = text("发现").findOne().bounds()var x = bounds.centerX();var y = bounds.centerY();click(x,y);sleep(3000)var btn_pyq = text("朋友圈").findOne();x = btn_pyq.bounds().centerX();y = btn_pyq.bounds().centerY();click(x,y);sleep(1000);var android_widget = className("android.widget.ListView")while(true){/* Scroll through friends */android_widget.scrollDown();sleep(1000);}}auto.waitFor();// home();var app_name = "微信"app.launchApp(app_name);sleep(1000)print_lian_xi_ren();cha_kan_peng_you_quan()
事件与监听 – Events详细讲解
From (事件与监听 – Events详细讲解 QQ消息、微信消息 通知服务 ):https://www.bilibili.com/video/BV14g4y1q7mr
/*Waiting for interface appear in three ways*///方法 1while(true){if(text("控件上的文字").exists()){break;}}//方法2text("控件上的文字").waitFor();//方法3text("控件上的文字").findOne();
示例:
// 启用按键监听evenntsevents.observeKey();// 监听音量 上键 按下events.onKeyDown("volume_up", function(event){toast("The volume button is pressed on the");});events.onKeyDown('volume_down', function(){toast("Menu button is pressed");exit();});events.on("key", function(key_code, event){if(key_code == keys.volume_up && envets.getAction() == event.ACTION_UP){toast("Menu button is pressed");}});events.observeNotification();events.onNotification(function(notification){printNotification(notification)});function printNotification(notification){log("应用包名:" + notification.getPackageName());log("通知文本:" + notification.getText());log("通知优先级:" + notification.priority);log("Notification Directory:" + notification.category);log("通知时间:" + new Date(notification.when));log("通知数:" + notification.number);log("通知摘要:" + notification.tickerText);}
事件与监听 – 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.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, listener)
- EventEmitter.removeAllListeners([eventName])
- EventEmitter.removeListener(eventName, listener)
- EventEmitter.setMaxListeners(n)
- events.broadcast: 脚本间广播
4、图片 和 颜色
Auto.js 从入门到精通:https://www.bilibili.com/video/av715713093/
找图、找色
images 模块提供了一些手机设备中常见的图片处理函数,包括截图、读写图片、图片剪裁、旋转、二值化、找色找图等.
:Auto.js
该模块分为两个部分:
- Look for the figure color part
- 图片处理部分
示例代码:
颜色转换方法/*// Return to color worthy of string,格式为 "#AARRGGBB"colors.toString(colorNum)colors.red(Num | str) // 返回颜色 color 的 R 通道的值,范围 0~255colors.green(Num | str) // 返回颜色 color 的 G 通道的值,范围 0~255colors.blue(Num | str) // 返回颜色 color 的 B 通道的值,范围 0~255colors.alpha(Num | str) // 返回颜色 color 的 alpha (透明度) 的值,范围 0~255// 返回 redNum, greenNum, blueNum In the composition of color value,alpha为255,即不透明colors.rgb(redNum, greenNum, blueNum)colors.argb(alpha, redNum, greenNum, blueNum)// 返回颜色的整数值colors.parseColor(colorStr)*/Whether the color is similar or equalif(!requestScreenCapture()) {toast("请求截图权限失败");exit();}toast("Requested screenshots permissions successful")sleep(5000);function getImg(x1, y1, x2, y2, imgSavePath){var screen = images.captureScreen();var img = images.clip(screen, x1, y1, x2-x1, y2-y1);img.saveTo(imgSavePath);img.recycle();}// Save the path of the directory must existgetImg(0,0,100,500,"/sdcard/Download/test.png");// 使用线程// thread.start(function(){// // In a new thread that executes the code// while(true){// if(text("立即执行").findOne()){// text("立即执行").findOne().click();// }else{// sleep(3000);// }// }// })
images 中的 requestScreenCapture、captureScreen These two functions that could be used as a global function to.注意:captureScreen 返回的图片,不需要进行回收…
在图片中寻找颜色、以及 point 对象
示例代码:
// images.findColor(image, color, options)// findColor(image, color, options) // 全局函数// Loop for color sampleimages.requestScreenCapture();// 循环找色,Find red (#ff0000) 时停止,And returns the coordinateswhile(true){var img = images.captureScreen();var point = images.findColor(img, "#ff0000");if(point){toast("找到 '红色',坐标为(" + point.x + "," + point.y + ")")break}sleep(500);}//Area to find the color sample//读取本地图片 /sdcard/1.pngvar img = images.read("/sdcard/1.png");// 判断图片是否加载成功if(!img){toast("Not found to load images");exit();}// 在该图片中找色.// Looking for color area specified:位置(400,500)的宽为300长为200的区域,指定找色临界值为4var point = findColor(img, "#00ff00", {region:[400,500,300,200],threshold: 4});if(point){toast("找到位置:" + point);}else{toast("没有找到");}
区域找色 — 简单方法
findColorInRegion(img, color, x, y, width, height, threshold);// 或者images.findColorInRegion(img, color, x, y, width, height, threshold);
Looking for color completely equal points in images
示例:Auto.js
images.findColorEquals(img, color[, x, y, width, height])
img
{Image} 图片color
{number} | {string} To find the color of thex
{number} Abscissa to find color area in the upper left cornery
{number} Looking for color area in the upper left corner ordinatewidth
{number} To find the width of the color areaheight
{number} To find the height of the color area- 返回 {Point}
在图片imgFound in the designated area color andcolorCompletely equal to a certain point,And return to the left of the point at which a;如果没有找到,则返回null
.
Find color area byx
,y
,width
,height
指定,If you do not specify find color area,Are found in the whole picture.
该函数也可以作为全局函数使用.
示例: (通过找QQThe color of the red dot to determine whether there is unread messages)
示例代码:
requestScreenCapture();launchApp("QQ");sleep(1200);var p = findColorEquals(captureScreen(), "#f64d30");if(p){toast("有未读消息");}else{toast("没有未读消息");}
多点找色
images.findMultiColors(img, firstColor, colors[, options])
img
{Image} Looking for color imagesfirstColor
{number} | {string} 第一个点的颜色colors
{Array} 表示剩下的点相对于第一个点的位置和颜色的数组,数组的每个元素为[x, y, color]options
{Object} 选项,包括:region
{Array} 找色区域.是一个两个或四个元素的数组.(region[0], region[1])表示找色区域的左上角;region[2]*region[3]表示找色区域的宽高.如果只有region只有两个元素,则找色区域为(region[0], region[1])To screen the bottom right hand corner.如果不指定region选项,则找色区域为整张图片.threshold
{number} 找色时颜色相似度的临界值,范围为0~255(越小越相似,0为颜色相等,255为任何颜色都能匹配).默认为4.threshold和浮点数相似度(0.0~1.0)的换算为 similarity = (255 – threshold) / 255.
多点找色,Similar to the wizard button to find more color,其过程如下:
- 在图片imgFind the colorfirstColor的位置(x0, y0)
- 对于数组colors的每个元素[x, y, color],检查图片img在位置(x + x0, y + y0)On whether the pixel colorcolor,是的话返回(x0, y0),否则继续寻找firstColor的位置,重新执行第1步
- The whole picture can’t find the return
null
例如,对于代码images.findMultiColors(img, "#123456", [[10, 20, "#ffffff"], [30, 40, "#000000"]])
,Suppose images in(100, 200)The location of the color#123456, 这时如果(110, 220)The location of the color#fffff且(130, 240)The location of the color#000000,The function return point(100, 200).
If you want to specify find color area,则在options中指定,例如:
var p = images.findMultiColors(img, "#123456", [[10, 20, "#ffffff"], [30, 40, "#000000"]], {region: [0, 960, 1080, 960]});
示例代码:
/*images.findMultiColors(img, firstColor, [color_1, color_2, ...], options);示例:images.findMultiColors(img, "#123456", [[10,20,"#ffffff"], [30,40,"#000000"]], options);images.findMultiColors(img, "#123456", [[5,10,"#ffffff"], [15,20,"#123456"]], {threshold:0});*/if(!images.requestScreenCapture()){toast("请求截图权限失败");exit();}text("微信").waitFor();sleep(1500);var img = images.captureScreen();sleep(500);// Get a point in the picture colorvar color_1 = img.pixel(100, 200);log(colors.toString(color_1));var color_point = images.findMultiColors(img, "#0d0e22",[[10,20, "#ffffff"], [30,40, "#000000"] ]);// The color of the print to find the coordinates of pointlog(color_point);
A particular location in the picture a particular color
images.detectsColor(image, color, x, y[, threshold = 16, algorithm = “diff”]):Auto.js
image
{Image} 图片color
{number} | {string} 要检测的颜色x
{number} To detect the location of the abscissay
{number} To detect the location of the ordinatethreshold
{number} Color similarity threshold,默认为16.取值范围为0~255.algorithm
{string} Color matching algorithm,包括:- “equal”: 相等匹配,Only with a given colorcolorFully equal to match.
- “diff”: Difference matching.With a given colorR、G、BThe absolute value of difference is less than the sum ofthreshold时匹配.
“rgb”: rgbEuler distance similarity.With a given colorcolor的rgbEuler distance less than or equal tothreshold时匹配.
“rgb+”: 加权rgbEuler distance matching(LAB Delta E).
- “hs”: hsEuler distance matching.hs为HSVOf the space tonal value.
返回图片image在位置(x, y)To match the colorcolor.A particular location in the images used in the detection of specific color.
A judge microblogging account side a weibo ever been thumb up examples of:
if(!requestScreenCapture()){toast("请求截图权限失败");exit();}text("排行榜").waitFor();sleep(1000);//找到点赞控件.// find() Does not block action,// findOne() 会阻塞操作,Until I find a continuing the follow-up processvar like = id("com.tencent.mm:id/bo_").find();//To obtain the control point coordinatesvar x = like.bounds().centerX();var y = like.bounds().centerY();//截图var img = captureScreen();//Whether in the coordinate of color is orange redif(images.detectsColor(img, "#fed9a8", x, y)){//Is it already a thumb up before,不做任何动作}else{//Otherwise click on the thumb up buttonlike.click();}
5、应用 — 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):
打开应用的详情页(设置页).如果找不到该应用,返回false; 否则返回true.该函数也可以作为全局函数使用.
- app.viewFile(path)
- app.editFile(path)
- app.uninstall(packageName)
- app.openUrl(url):用浏览器打开网站 url.如果没有安装浏览器应用,则抛出ActivityNotException.
- app.sendEmail(options):
options
{Object} 发送邮件的参数.包括:email
{string} | {Array} 收件人的邮件地址.如果有多个收件人,则用字符串数组表示cc
{string} | {Array} 抄送收件人的邮件地址.如果有多个抄送收件人,则用字符串数组表示bcc
{string} | {Array} 密送收件人的邮件地址.如果有多个密送收件人,则用字符串数组表示subject
{string} 邮件主题(标题)text
{string} 邮件正文attachment
{string} 附件的路径.
根据选项 options 调用邮箱应用发送邮件.这些选项均是可选的.如果没有安装邮箱应用,则抛出
ActivityNotException
.//发送邮件给10086@qq.com和10001@qq.com.app.sendEmail({email: ["10086@qq.com", "10001@qq.com"],subject: "这是一个邮件标题",text: "这是邮件正文"});
- app.startActivity(name):启动 Auto.js 的特定界面.该函数在 Auto.js 内运行则会打开 Auto.js内的界面,在打包应用中运行则会打开打包应用的相应界面.name {string} 活动名称,可选的值为:console 日志界面、settings 设置界面
示例代码:
// app.openAppSetting(app.getPackageName("微信"));// sleep(1000)// app.openAppSetting(app.getPackageName("QQ"));// sleep(1000)app.startActivity("console");sleep(1000)app.startActivity("settings")//app.openUrl("https://www.baidu.com")//sleep(1000)
6、进阶: 意图 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)
7、悬浮窗 —Floaty
floaty Module provides a suspended the correlation function of the window,Can be displayed on the screen the custom floating window,Control of suspension window size、位置等.Floating window stops the script automatically shut down,因此,To keep the floating window is not closed,可以用一个空的setInterval 来实现,例如:setInterval(()=>{}, 1000);
floaty.window(layout)— 创建、关闭 悬浮窗
Create and close the floating window( ui 界面设置 ):Auto.js从入门到精通_哔哩哔哩_bilibili
layout
{xml} | {View} Floating window interfaceXML或者View
Specify the layout of the floating window,创建并显示A floating window,返回一个FloatyWindow
对象.
The floating window bringing close、调整大小、Adjust the position button,可根据需要调用setAdjustEnabled()
Function to show or hide.其中layout参数可以是xmlThe layout or aView,更多信息参见ui模块的说明.例子:
var w = floaty.window(悬浮文字);setTimeout(()=>{w.close();}, 2000);
After this code runs will suspended text on the screen,And disappear after two seconds.另外,Because the script is running thread is notUI线程,And all the controls modification operations need to be inUI线程执行,此时需要用ui.run
,例如:
ui.run(function(){w.text.setText("文本");});
完整示例:
// frame Is an overlapping layout,如果再添加 一个 button,The two will overlap to a// 更多布局,可以参看:https://hyb1996.github.io/AutoJs-Docs/#/ui?id=垂直布局-verticalvar w = floaty.window(悬浮文字);// setTimeout(()=>{// w.close();// }, 2000);setInterval(()=>{}, 1000); // Keep floating window is not closedui.run(function(){w.text.setText("文本");});
简单使用”垂直布局” 示例:
更多布局,可以参看:https://hyb1996.github.io/AutoJs-Docs/#/ui?id=垂直布局-vertical
var xuanfu_window = floaty.window(悬浮文字 text_1悬浮文字 text_2);setInterval(()=>{}, 1000);ui.run(function(){xuanfu_window.text_1.setText("text_1_text_1_text_1");xuanfu_window.text_2.setText("text_2_text_2_text_2");});
floaty.rawWindow(layout)—Specify the layout of the floating window
layout
{xml} | {View} Floating window interfaceXML或者View
Specify the layout of the floating window,创建并显示An original floating window,返回一个FloatyRawWindow
对象.与floaty.window()
函数不同的是,The floating window will not add any additional facilities(例如调整大小、位置按钮),You can according to their own need to write any layout.而且,The suspended support completely full screen window,You can override the status bar,So can do eye patterns such as application of.示例代码:
var xfc_1 = floaty.rawWindow(悬浮文字);var xfc_2 = floaty.rawWindow(悬浮文字);setInterval(()=>{}, 1000);xfc_2.setPosition(500, 500);
floaty.closeAll()— Close all the script floating window.
Floating window object —FloatyWindow
Get on the interface of the floating window elements —FloatyWindow.{id}
Floating window object,可通过FloatyWindow.{id}
Get on the interface of the floating window elements.例如, 悬浮窗 window On a control id 为 aaa, 那么window.aaa
Available to the control,类似于 ui.
下面的 window 都是指FloatyWindow 对象,而不是FloatyRawWindow
window.setAdjustEnabled(enabled)
enabled
{boolean} Whether to enable floating window adjust(大小、位置).如果 enabled 为 true,In the suspension left upper corner of the window、The upper right corner of the display for position、Adjust to the size of the label,Just like the console; 如果 enabled 为 false,Hides the label.
var xfc_1 = floaty.window(悬浮文字);xfc_1.setAdjustEnabled(true);// xfc_1.setSize(-1, -1); // -1 Said calculated on the maximum,占满整个屏幕xfc_1.setSize(500, 500);setInterval(()=>{}, 1000);
window.setPosition(x, y)
For floating window position.
window.getX()
Returns the floating window positionX坐标.
window.getY()
Returns the floating window positionY坐标.
window.setSize(width, height)
For floating window width high.
window.getWidht()
Return floating window width.
window.getHeight()
Return floating window height.
window.close()
关闭悬浮窗.If the floating window is closed,This function will not do anything.
window.exitOnClose()
Suspended window closes automatically when the end of the script is running.
原始 Floating window object —FloatyRawWindow
The original floating window object,可通过window.{id}
Get on the interface of the floating window elements.例如, 悬浮窗windowOn a controlid为aaa, 那么window.aaa
Available to the control,类似于ui.
window.setTouchable(touchable)
touchable
{Boolean} 是否可触摸
设置悬浮窗是否可触摸,如果为true, 则悬浮窗将接收到触摸、点击等事件并且无法继续传递到悬浮窗下面;如果为false, 悬浮窗上的触摸、点击等事件将被直接传递到悬浮窗下面.处于安全考虑,Be suspended window to receive the touch of it can no longer continue to be passed to the lower level.
Can use this feature to make the model script that shield an eye,示例代码:
var w = floaty.rawWindow();w.setSize(-1, -1); // -1 Said calculated on the maximum,占满整个屏幕w.setTouchable(false);setTimeout(()=>{w.close();}, 4000);
8、脚本引擎
:Auto.js
在脚本引擎中运行脚本
engines.execScript(name, script[, config])
name
{string} 要运行的脚本名称.这个名称和文件名称无关,只是在任务管理中显示的名称.script
{string} 要运行的脚本内容.config
{Object} 运行配置项delay
{number} 延迟执行的毫秒数,默认为0loopTimes
{number} 循环运行次数,默认为1.0为无限循环.interval
{number} 循环运行时两次运行之间的时间间隔,默认为0path
{Array} | {string} 指定脚本运行的目录.这些路径会用于require时寻找模块文件.
在新的脚本环境中运行脚本script.返回一个ScriptExectuion对象.
所谓新的脚本环境,指定是,脚本中的变量和原脚本的变量是不共享的,并且,脚本会在新的线程中运行.
最简单的例子如下:engines.execScript(“hello world”, “toast(‘hello world’)”);
If you want to loop running,则:
//每隔3秒运行一次脚本,循环10次engines.execScript("hello world", "toast('hello world')", {loopTimes: 10,interval: 3000});
Use the string to write a script very inconvenient,可以结合Function.toString()
Methods to perform a specific function:
function helloWorld(){//注意,The Shared variables and script main body is nottoast("hello world");}engines.execScript("hello world", "helloWorld();\n" + helloWorld.toString());
If you want to pass variables,You can put these encapsulated into a function:
function exec(action, args){args = args || {};engines.execScript(action.name, action + "(" + JSON.stringify(args) + ");\n" + action.toString());}//要执行的函数,Is a simple additionfunction add(args){toast(args.a + args.b);}//In the new script environment to perform 1 + 2exec(add, {a: 1, b:2});
综合示例代码:
// toast("The script engine sample")// // 示例 1// engines.execScript("js_engines_test", 'toast("示例 1");home();', {// delay: 2000,// loopTimes: 3,// interval: 2000// });// // 示例 2// function func_test(){// toast("示例 2");// }// engines.execScript("js_test", func_test.toString() + "func_test();")// 示例 3function func_aaa(args){toast(args.a + args.b);}function func_exec(func, args){console.log(func.toString());console.log(args.toString());args = args || {};var func_to_string = func.toString();var re_string = /function\s*(\w*)/i;var result_list = re_string.exec(func_to_string);var func_name = result_list[1];engines.execScript(func_name, func.toString()+func_name+"("+JSON.stringify(args)+");")}func_exec(func_aaa, {a:10, b:20});
在脚本引擎中运行 js 文件
engines.execScriptFile(path[, config])
path
{string} 要运行的脚本路径.config
{Object} 运行配置项delay
{number} 延迟执行的毫秒数,默认为0loopTimes
{number} 循环运行次数,默认为1.0为无限循环.interval
{number} 循环运行时两次运行之间的时间间隔,默认为0path
{Array} | {string} 指定脚本运行的目录.这些路径会用于require时寻找模块文件.
在新的脚本环境中运行脚本文件path.返回一个ScriptExecution对象.
engines.execScriptFile("/sdcard/脚本/1.js");
在脚本引擎中运行录制的脚本文件
fasengines.execAutoFile(path[, config])
path
{string} 要运行的录制文件路径.config
{Object} 运行配置项delay
{number} 延迟执行的毫秒数,默认为0loopTimes
{number} 循环运行次数,默认为1.0为无限循环.interval
{number} 循环运行时两次运行之间的时间间隔,默认为0path
{Array} | {string} 指定脚本运行的目录.这些路径会用于require时寻找模块文件.
在新的脚本环境中运行录制文件path.返回一个ScriptExecution对象.
engines.execAutoFile("/sdcard/脚本/1.auto");
The script engine control method
engines.stopAll()
停止所有正在运行的脚本.包括当前脚本自身.
engines.stopAllAndToast()
停止所有正在运行的脚本并显示停止的脚本数量.包括当前脚本自身.
engines.execScript("test_test", "sleep(10000);");sleep(3000);engines.stopAllAndToast();
engines.myEngine()
返回当前脚本的脚本引擎对象(ScriptEngine)
[v4.1.0新增]特别的,该对象可以通过execArgv
来获取他的运行参数,包括外部参数、intent等.例如:
log(engines.myEngine().execArgv);
普通脚本的运行参数通常为空,通过定时任务的广播启动的则可以获取到启动的intent.
engines.all()
- 返回 {Array}
Returns the current all running script script engineScriptEngine的数组.
log(engines.all());
脚本执行对象 —ScriptExecution
执行字符串 js 或者 文件 js 时,返回的对象,就是ScriptExecution 对象
脚本执行对象:Auto.js
执行脚本时返回的对象,Can he obtain the execution engine、配置等,也可以停止这个执行.
To stop the execution of the script,使用exectuion.getEngine().forceStop()
.
ScriptExecution.getEngine()
Return to execute the script of the script engine object(ScriptEngine)
ScriptExecution.getConfig()
返回该脚本的运行配置(ScriptConfig)
脚本引擎对象 — ScriptEngine
:Auto.js
脚本执行的过程中,会返回一个 js 引擎,即 js 的执行环境,就是 脚本引擎对象
脚本引擎对象.
ScriptEngine.forceStop()
停止脚本引擎的执行.
ScriptEngine.cwd()
- 返回 {string}
返回脚本执行的路径.对于一个脚本文件而言为这个脚本所在的文件夹;对于其他脚本,例如字符串脚本,则为null
或者执行时的设置值.
ScriptEngine.getSource()
- 返回ScriptSource
返回当前脚本引擎正在执行的脚本对象.
log(engines.myEngine().getSource());
示例代码:
var script_execution_obj = engines.execScriptFile("/sdcard/脚本/demo.js");sleep(1000);var script_engine = script_execution_obj.getEngine()log("脚本引擎对象 ---> " + script_engine);var script_config = script_execution_obj.getConfig()log("脚本运行配置 ---> " + script_config);log("执行路径 ---> " + script_engine.cwd());log("脚本源码 ---> " + script_engine.getSource());script_engine.forceStop()
Communications between the basic engine
ScriptEngine.emit(eventName[, …args])
eventName
{string} 事件名称...args
{any} 事件参数
向该脚本引擎发送一个事件,This event can be the corresponding script in the script engineeventsModule and listen to the main thread in the script execution event processing.
例如脚本receiver.js的内容如下:
//监听say事件events.on("say", function(words){toastLog(words);});//保持脚本运行setInterval(()=>{}, 1000);
The same directory to another script can start him and send it:
//运行脚本var e = engines.execScriptFile("./receiver.js");//等待脚本启动sleep(2000);//向该脚本发送事件e.getEngine().emit("say", "你好");
脚本配置
:Auto.js
脚本执行时的配置.
delay
- {number}
延迟执行的毫秒数
interval
- {number}
循环运行时两次运行之间的时间间隔
loopTimes
- {number}
循环运行次数
getPath()
- 返回 {Array}
返回一个字符串数组表示脚本运行时模块寻找的路径.
9、用户界面 — UI
From:https://www.bilibili.com/video/BV1pQ4y1R7Us?p=61
Auto.js教程(第十四期)-界面UI教程(全网最全最详细):https://www.bilibili.com/video/BV1cy4y117iY
Interface design is similar to HTML
ui Write the user interface module provides a support.带有 ui 的脚本的的最前面必须使用"ui";
指定 ui 模式,否则脚本将不会以 ui 模式运行.正确示范:
"ui";//Other script code
字符串 “ui” In the front of the can have comments、空行和空格[v4.1.0新增],But there can be no other code.
视图(View)— ( 控件、布局 )
界面 是由 视图(View) 组成的.View 分成两种:
- 控件(Widget).控件 (Widget) Used to display text specific、图片、网页等,比如文本控件(text)用来显示文字,按钮控件(button)You can display and provide a button click effect,图片控件(img)Is used to display images from network or file,In addition to the input box control(input)、进度条控件(progressbar)、Radio check box control(checkbox)等;
- 布局(Layout).布局 (Layout) Is filled with one or more control “容器”,Position of controls is used to control in him,比如 垂直布局(vertical) Will put him inside control in turn down on display(The vertical arrangement),水平布局(horizontal) Will put him in control from left to right in turn display(即横向排列),以及 帧布局(frame),He will put him inside control directly in the upper left corner to show,如果有多个控件,At the back of the control will overlap in the previous control.
我们使用 xml 来编写界面,并通过ui.layout()
The layout of the function specifies the interface xml.举个例子:
"ui";ui.layout();
垂直布局(vertical) 改成 水平布局(horizontal)
"ui";ui.layout();
A control can specify more than one attribute(Even can not specify any properties),用空格隔开即可;Layout also can specify properties,例如:
"ui";ui.layout();
第三行bg="#ff0000"
Specifies the background color of vertical layout(bg)为”#ff0000″,这是一个RGB颜色,表示红色(有关RGBKnowledge of relevant seeRGB颜色对照表).第四行的textSize="20sp"
Specifies the button control the font size(textSize)为”20sp”,spIs a font unit,Without further notice.
An interface is composed of some layout and control.
- 子视图, 子控件: The control layout is the layout of child controls/子视图.In fact layout inside not only has the control,Can also be nested layout.Therefore use child view(Child View)更准确一些.在上面的例子中,Button is vertical layout of child controls.
- 父视图,父布局:Directly include the layout of a control is the control of the parent layout/父视图(Parent View).在上面的例子中,Vertical layout is the father of button layout.
更多 view 的属性:https://hyb1996.github.io/AutoJs-Docs/#/ui?id=视图-view
Autojs 示例代码
视频教程:Auto.js从入门到精通_哔哩哔哩_bilibili
如图所示:
文本控件
输入框控件
按钮控件
图片控件
表格控件
单选框控件、复选框控件
进度条控件
卡片布局
列表控件
时间日期控件
下拉菜单控件
一般全局函数
全局变量和函数在所有模块中均可使用. 但以下变量的作用域只在模块内,详见module:
- exports
- module
- require() 以下的对象是特定于 Auto.js 的. 有些内置对象是 JavaScript 语言本身的一部分,它们也是全局的.
一些模块中的函数为了使用方便也可以直接全局使用,这些函数在此不再赘述.例如timers模块的setInterval, setTimeout等函数.
- 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
示例代码:
var _toast = toast;toast = function(msg){_toast(msg);sleep(2000);}toast("123");toast("456");toast("789");
// text("微信").waitFor();// sleep(1000);// There are no waiting for a page,则一直等待// waitForActivity("com.tencent.mm.plugin.sns.ui.SnsTimeLineUI");// toast("Has reached the WeChat interface");waitForPackage("com.tencent.mm");toast("Has come to an application");var 控件集合 = id("com.miui.home:id/icon_icon").findOne();var 控件数量 = 控件数量.size();var r = random(0, 控件数量-1);var 控件坐标 = 控件集合.get(r).bounds();click(控件坐标.centerX(), 控件坐标.centerY())
控制台
Console a suspended window,Operations such as simulated click is unable to penetrate the content behind the operation of…
控制台模块提供了一个和 Web 浏览器中相似的用于调试的控制台.用于输出一些调试信息、中间结果等. console 模块中的一些函数也可以直接作为全局函数使用,例如 log, print 等.
显示、隐藏 控制台
- console.show():显示控制台.这会显示一个控制台的悬浮窗(需要悬浮窗权限).
- console.hide():隐藏控制台悬浮窗.
控制台信息 清理、打印
console.clear()
清空控制台.
console.log([data][, …args])
data
{any}...args
{any}
打印到控制台,并带上换行符. 可以传入多个参数,第一个参数作为主要信息,其他参数作为类似于printf(3)中的代替值(参数都会传给 util.format()).
const count = 5;console.log('count: %d', count);// 打印: count: 5 到 stdoutconsole.log('count:', count);// 打印: count: 5 到 stdout
详见 util.format().该函数也可以作为全局函数使用.
print(text)
- text {string} | {Object} 要打印到控制台的信息
相当于log(text)
.
console.trace([data][, …args])
[v4.1.0新增]
data
{any}...args
{any}
与 console.log 类似,同时会打印出调用这个函数所在的调用栈信息(即当前运行的文件、行数等信息).
console.trace('Show me');// 打印: (堆栈跟踪会根据被调用的跟踪的位置而变化)// Show me// at :7
The console output information style
console.verbose([data][, …args])
data
{any}...args
{any}
与 console.log 类似,但输出结果以灰色字体显示.输出优先级低于log,用于输出观察性质的信息.
console.info([data][, …args])
data
{any}...args
{any}
与console.log类似,但输出结果以绿色字体显示.输出优先级高于log, 用于输出重要信息.
console.warn([data][, …args])
data
{any}...args
{any}
与console.log类似,但输出结果以蓝色字体显示.输出优先级高于info, 用于输出警告信息.
console.error([data][, …args])
data
{any}...args
{any}
与console.log类似,但输出结果以红色字体显示.输出优先级高于warn, 用于输出错误信息.
console.assert(value, message)
- value {any} 要断言的布尔值
- message {string} value为false时要输出的信息
断言.如果value为false则输出错误信息message并停止脚本运行.
var a = 1 + 1;console.assert(a == 2, "加法出错啦");
Console timing
console.time([label])
[v4.1.0新增]
label
{String} 计时器标签,可省略
启动一个定时器,用以计算一个操作的持续时间. 定时器由一个唯一的label
标识. 当调用console.timeEnd()
时,可以使用相同的label
来停止定时器,并以毫秒为单位将持续时间输出到控制台. 重复启动同一个标签的定时器会覆盖之前启动同一标签的定时器.
console.timeEnd(label)
[v4.1.0新增]
label
{String} 计时器标签
停止之前通过调用console.time()
启动的定时器,并打印结果到控制台. 调用console.timeEnd()
后定时器会被删除.如果不存在标签指定的定时器则会打印NaNms
.
console.time('求和');var sum = 0;for(let i = 0; i < 100000; i++){sum += i;}console.timeEnd('求和');// 打印 求和: xxx ms
控制台输入
console.input(data[, …args])
data
{any}...args
{any}
与console.log一样输出信息,并在控制台显示输入框等待输入.按控制台的确认按钮后会将输入的字符串用eval计算后返回.
部分机型可能会有控制台不显示输入框的情况,属于bug.
例如:
var n = console.input("请输入一个数字:");//输入123之后:toast(n + 1);//显示124
console.rawInput(data[, …args])
data
{any}...args
{any}
与console.log一样输出信息,并在控制台显示输入框等待输入.按控制台的确认按钮后会将输入的字符串直接返回.
部分机型可能会有控制台不显示输入框的情况,属于bug.
例如:
var n = console.rawInput("请输入一个数字:");//输入123之后:toast(n + 1);//显示1231
console size、位置、配置的设置
console.setSize(w, h)
w
{number} 宽度h
{number} 高度
设置控制台的大小,单位像素.
console.show();sleep(2000);console.setSize(device.width/2, device.height/2)
console.setPosition(x, y)
x
{number} 横坐标y
{number} 纵坐标
设置控制台的位置,单位像素.
console.show();console.setPosition(100, 100);
console.setGlobalLogConfig(config)
[v4.1.0新增]
config
{Object} 日志配置,可选的项有:file
{string} 日志文件路径,将会把日志写入该文件中maxFileSize
{number} 最大文件大小,单位字节,默认为512 * 1024 (512KB)rootLevel
{string} 写入的日志级别,默认为”ALL”(所有日志),可以为”OFF”(关闭), “DEBUG”, “INFO”, “WARN”, “ERROR”, “FATAL”等.maxBackupSize
{number} 日志备份文件最大数量,默认为5filePattern
{string} 日志写入格式,参见PatternLayout
设置日志保存的路径和配置.例如把日志保存到”/sdcard/1.txt”:
console.setGlobalLogConfig({"file": "/sdcard/1.txt"});
注意该函数会影响所有脚本的日志记录.
安卓7.0 以上的 触摸 和 手势模拟
:https://pro.autojs.org/docs/#/zh-cn/coordinatesBasedAutomation?id=安卓70The above touch and gesture to simulate
免 root 手机 “模拟点击” 的三种方式
1. click(x, y)
x
{number} 要点击的坐标的x值y
{number} 要点击的坐标的y值
模拟点击坐标(x, y),并返回是否点击成功.只有在点击执行完成后脚本才继续执行.
一般而言,只有点击过程 ( 大约 150ms) 中被其他事件中断 ( 例如 用户自行点击 ) 才会点击失败.
Use this function to simulate continuous clicked,May have problems with click speed too slow,这时可以用 press() 函数代替
2. longClick(x, y)
x
{number} 要长按的坐标的x值y
{number} 要长按的坐标的y值
模拟长按坐标(x, y), 并返回是否成功.只有在长按执行完成(大约600毫秒)时脚本才会继续执行.一般而言,只有长按过程中被其他事件中断(例如用户自行点击)才会长按失败.
3. press(x, y, duration)
x
{number} To hold the coordinates of thex值y
{number} To hold the coordinates of they值duration
{number} Press and hold for how long,单位毫秒
模拟按住坐标(x, y), 并返回是否成功.只有按住操作执行完成时脚本才会继续执行.
If the hold time is too short,Is possessed by a system that is click;如果时长超过500毫秒,则认为是长按.
一般而言,Only hold by other events in the process of interruption will fail.
A point of example as follows:
//循环100次for(var i = 0; i < 100; i++){//点击位置(500, 1000), 每次用时1毫秒press(500, 1000, 1);}
免 root 手机 “模拟滑动”的三种方式
swipe(x1, y1, x2, y2, duration)
x1
{number} 滑动的起始坐标的x值y1
{number} 滑动的起始坐标的y值x2
{number} 滑动的结束坐标的x值y2
{number} 滑动的结束坐标的y值duration
{number} 滑动时长,单位毫秒
模拟从坐标(x1, y1)滑动到坐标(x2, y2),并返回是否成功.只有滑动操作执行完成时脚本才会继续执行.一般而言,只有滑动过程中被其他事件中断才会滑动失败.
gesture(duration, [x1, y1], [x2, y2], …)
duration
{number} 手势的时长- [x, y] … 手势滑动路径的一系列坐标
模拟手势操作.例如gesture(1000, [0, 0], [500, 500], [500, 1000])
为模拟一个从(0, 0)到(500, 500)到(500, 100)的手势操作,时长为2秒.
gestures([delay1, duration1, [x1, y1], [x2, y2], …], [delay2, duration2, [x3, y3], [x4, y4], …], …)
同时模拟多个手势.每个手势的参数为[delay, duration, 坐标], delay为延迟多久(毫秒)才执行该手势;duration为手势执行时长;坐标为手势经过的点的坐标.其中delay参数可以省略,默认为0.
Such as kneading finger:
gestures([0, 500, [100, 500], [100, 1000]],[0, 500, [300, 500], [300, 1000]],[0, 500, [500, 500], [500, 1000]]);
使用 root 权限 点击 和 滑动
RootAutomator 是一个使用 root 权限来模拟触摸的对象,用它可以完成触摸与多点触摸,并且这些动作的执行没有延迟.一个脚本中最好只存在一个RootAutomator,并且保证脚本结束退出他.可以在exit事件中退出RootAutomator,例如:
var ra = new RootAutomator();events.on('exit', function(){ra.exit();});//Click to perform some operation...
注意:以下命令需要root权限
RootAutomator
RootAutomator是一个使用root权限来模拟触摸的对象,用它可以完成触摸与多点触摸,并且这些动作的执行没有延迟.
一个脚本中最好只存在一个RootAutomator,并且保证脚本结束退出他.可以在exit事件中退出RootAutomator,例如:
var ra = new RootAutomator();events.on('exit', function(){ra.exit();});//Click to perform some operation...
Pay attention to the following commands need toroot权限
RootAutomator.tap(x, y[, id])
x
{number} 横坐标y
{number} 纵坐标id
{number} 多点触摸id,可选,默认为1,可以通过setDefaultId指定.
点击位置(x, y).其中id是一个整数值,用于区分多点触摸,不同的id表示不同的”手指”,例如:
var ra = new RootAutomator();//让"手指1"点击位置(100, 100)ra.tap(100, 100, 1);//让"手指2"点击位置(200, 200);ra.tap(200, 200, 2);ra.exit();
如果不需要多点触摸,则不需要id这个参数. 多点触摸通常用于手势或游戏操作,例如模拟双指捏合、双指上滑等.
某些情况下可能存在tap点击无反应的情况,这时可以用RootAutomator.press()
函数代替.
RootAutomator.swipe(x1, x2, y1, y2[, duration, id])
x1
{number} 滑动起点横坐标y1
{number} 滑动起点纵坐标x2
{number} 滑动终点横坐标y2
{number} 滑动终点纵坐标duration
{number} 滑动时长,单位毫秒,默认值为300id
{number} 多点触摸id,可选,默认为1
Simulate once from(x1, y1)到(x2, y2)的时间为duration毫秒的滑动.
RootAutomator.press(x, y, duration[, id])
x
{number} 横坐标y
{number} 纵坐标duration
{number} 按下时长id
{number} 多点触摸id,可选,默认为1
Simulated press position(x, y),时长为duration毫秒.
RootAutomator.longPress(x, y[, id])
x
{number} 横坐标y
{number} 纵坐标duration
{number} 按下时长id
{number} 多点触摸id,可选,默认为1
Long simulation according to the position(x, y).
以上为简单模拟触摸操作的函数.如果要模拟一些复杂的手势,需要更底层的函数.
RootAutomator.touchDown(x, y[, id])
x
{number} 横坐标y
{number} 纵坐标id
{number} 多点触摸id,可选,默认为1
Simulation finger to press the position(x, y).
RootAutomator.touchMove(x, y[, id])
x
{number} 横坐标y
{number} 纵坐标id
{number} 多点触摸id,可选,默认为1
Simulated moving fingers to position(x, y).
RootAutomator.touchUp([id])
id
{number} 多点触摸id,可选,默认为1
模拟手指弹起.
In the subsequent version is likely to have the following function changes!Please do not rely too much on.推荐使用RootAutomator
Replace the touch of this section function.
The following function to beroot权限,Can realize click anywhere、滑动等.
- These functions are usually capitalize the first letter to show its special permission.
- These functions are not return anything.
- 并且,The execution of these functions is asynchronous、非阻塞的,In the different models on the time.The script will not wait for action completes to continue.So it’s best after each function with appropriatesleepTo achieve the desired effect.
例如:
Tap(100, 100);sleep(500);
注意,The execution of the actions may not be able to be stopped,例如:
for(var i = 0; i < 100; i++){Tap(100, 100);}
This code is executed may appear in the task management stop click continue after script. 因此,It is strongly recommended that after every action plus time delay:
for(var i = 0; i < 100; i++){Tap(100, 100);sleep(500);}
Tap(x, y)
- x, y {number} 要点击的坐标.
点击位置(x, y), 您可以通过”开发者选项”开启指针位置来确定点击坐标.
Swipe(x1, y1, x2, y2, [duration])
- x1, y1 {number} 滑动起点的坐标
- x2, y2 {number} 滑动终点的坐标
- duration {number} 滑动动作所用的时间
滑动.从(x1, y1)位置滑动到(x2, y2)位置.