### find Example
Source: http://autojs.cc/v8/automator/selector.html
Example of using find to get a collection of all matching UI elements and checking if the collection is empty.
```javascript
var c = className("AbsListView").find();
if(!c.empty()){
toast("找到啦");
}else{
toast("没找到╭(╯^╰)╮");
}
```
--------------------------------
### Example: Opening an image file with app.intent
Source: http://autojs.cc/v8/app.html
This example demonstrates how to construct an Intent to view a PNG image file using app.intent and then start the activity.
```javascript
//打开应用来查看图片文件
var i = app.intent({
action: "VIEW",
type: "image/png",
data: "file:///sdcard/1.png"
});
context.startActivity(i);
```
--------------------------------
### Get System Apps
Source: http://autojs.cc/v8/app.html
Example of how to get a list of system applications and specify the information to be returned, such as meta_data.
```javascript
// 获取系统app
let apps = $app.getInstalledApps({
get: ['meta_data'],
match: ['system_only']
});
console.log(apps);
```
--------------------------------
### $util.format Example 3
Source: http://autojs.cc/v8/util.html
Example showing the behavior when the first argument is not a string.
```javascript
$util.format(1, 2, 3); // '1 2 3'
```
--------------------------------
### $util.format Example 1
Source: http://autojs.cc/v8/util.html
Example demonstrating how placeholders are not replaced if no corresponding argument is provided.
```javascript
$util.format('%s:%s', 'foo');
// Returns: 'foo:%s'
```
--------------------------------
### Input Control Hint Example
Source: http://autojs.cc/v8/ui/basic.html
Example of an input field with a hint.
```javascript
"ui";
ui.layout(
);
```
--------------------------------
### on example
Source: http://autojs.cc/v8/events.html
Basic example of adding an event listener.
```javascript
server.on('connection', (stream) => {
console.log('有连接!');
});
```
--------------------------------
### Button Control Example
Source: http://autojs.cc/v8/ui/basic.html
Example of a colored button using a predefined AppCompat style.
```xml
```
--------------------------------
### $util.format Example 4
Source: http://autojs.cc/v8/util.html
Example showing that if only one argument is passed, it is returned as is.
```javascript
$util.format('%% %s'); // '%% %s'
```
--------------------------------
### $util.inspect Example
Source: http://autojs.cc/v8/util.html
Example demonstrating how to inspect the `$util` object with all properties.
```javascript
console.log($util.inspect($util, { showHidden: true, depth: null }));
```
--------------------------------
### eventNames example
Source: http://autojs.cc/v8/events.html
Example showing how to get an array of all registered event names.
```javascript
const myEE = events.emitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
```
--------------------------------
### $util.format Example 2
Source: http://autojs.cc/v8/util.html
Example showing how extra arguments are converted to strings and concatenated.
```javascript
$util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'
```
--------------------------------
### console.time and console.timeEnd example
Source: http://autojs.cc/v8/console.html
Starts a timer with a label and stops it, printing the duration in milliseconds to the console.
```javascript
console.time('求和');
var sum = 0;
for(let i = 0; i < 100000; i++){
sum += i;
}
console.timeEnd('求和');
// 打印 求和: xxx ms
```
--------------------------------
### $util.extend Example
Source: http://autojs.cc/v8/util.html
Example demonstrating how to inherit prototype methods from one constructor to another.
```javascript
function SuperClass() {
this.value = 1;
}
SuperClass.prototype.increment = function() {
this.value++;
}
$util.extend(ChildClass, SuperClass);
function ChildClass() {
SuperClass.call(this);
}
ChildClass.prototype.print = function () {
console.log(this.value);
}
let child = new ChildClass();
child.increment();
child.print();
```
--------------------------------
### Password Input Example
Source: http://autojs.cc/v8/ui/basic.html
Example of a password input field.
```xml
```
--------------------------------
### Capture Screen and Get Pixel Color
Source: http://autojs.cc/v8/images.html
Example of capturing the screen, getting the color of a specific pixel, and displaying it.
```javascript
// Request landscape screen capture
requestScreenCapture(true);
// Capture screen
var img = captureScreen();
// Get the color value at point (100, 100)
var color = images.pixel(img, 100, 100);
// Display the color value
tost(colors.toString(color));
```
--------------------------------
### Input Control Example
Source: http://autojs.cc/v8/ui/basic.html
Example of an input field with a button and event handling.
```javascript
"ui";
ui.layout(
);
//指定确定按钮点击时要执行的动作
ui.ok.click(function () {
//通过getText()获取输入的内容
var name = ui.name.getText().toString();
toast(name + "您好!");
});
```
--------------------------------
### Single Line Input Example
Source: http://autojs.cc/v8/ui/basic.html
Example of a single-line input field.
```xml
```
--------------------------------
### pm install options
Source: http://autojs.cc/v8/shell.html
Options for the 'pm install' command to install a package.
```shell
install [options] path
```
--------------------------------
### Input Type Example
Source: http://autojs.cc/v8/ui/basic.html
Example specifying input type as decimal numbers.
```xml
```
--------------------------------
### Input Dialog Example
Source: http://autojs.cc/v8/dialogs.html
Example of building a dialog with an input field and logging the input.
```javascript
dialogs.build({
title: "请输入您的年龄",
inputPrefill: "18"
}).on("input", (input)=>{
var age = parseInt(input);
toastLog(age);
}).show();
```
--------------------------------
### ColorMapping findColor Example (Multiple Finds)
Source: http://autojs.cc/v8/images.html
An example demonstrating how to repeatedly use ColorMapping to find different colors (white and black) within a screenshot in a loop.
```javascript
// 申请截图权限
$images.requestScreenCapture();
// 初始化ColorMapping
let ColorMapping = $colors.mapping;
// 创建ColorMapping实例
let cm = new ColorMapping();
// 使用ColorMapping找色
while (true) {
// 截屏
let img = $images.captureScreen();
// 初始化颜色映射
cm.reset(img);
let p1 = cm.findColor("#ffffff");
if (p1) {
// ...
console.log("白色点坐标" + p1);
continue;
}
let p2 = cm.findColor("#000000");
if (p2) {
// ...
console.log("黑色点坐标" + p2);
continue;
}
}
// 释放ColorMapping
cm.recycle();
```
--------------------------------
### $util.isBoolean Example 2
Source: http://autojs.cc/v8/util.html
Example showing `$util.isBoolean` returning false for zero.
```javascript
$util.isBoolean(0);
// Returns: false
```
--------------------------------
### $util.isArray Example 1
Source: http://autojs.cc/v8/util.html
Example showing `$util.isArray` returning true for an empty array.
```javascript
$util.isArray([]);
// Returns: true
```
--------------------------------
### $util.isArray Example 2
Source: http://autojs.cc/v8/util.html
Example showing `$util.isArray` returning true for an array created with `new Array()`.
```javascript
$util.isArray(new Array());
// Returns: true
```
--------------------------------
### autoLink Example
Source: http://autojs.cc/v8/ui/basic.html
Example demonstrating the use of autoLink to make URLs and phone numbers clickable.
```xml
```
--------------------------------
### Feature Matching Example
Source: http://autojs.cc/v8/images.html
An example demonstrating feature matching between a small template image and a captured screenshot. It calculates features for both, performs matching, and optionally draws the matches. The example also shows how to recycle feature objects to prevent memory leaks.
```javascript
// Read small image
let hellokitty = $images.read('./hellokitty.jpg');
// Calculate small image features
let objectFeatures = $images.detectAndComputeFeatures(hellokitty);
// Request screenshot permission
requestScreenCapture();
// Open HelloKitty image
$app.openUrl('https://baike.baidu.com/item/Hello%20Kitty/984270')
let n = 3;
for (let i = 0; i < n; i++) {
sleep(3000);
let capture = captureScreen();
// To improve efficiency, you can adjust the scale parameter when calculating large image features. The default is 0.5.
// Smaller values are faster but may lead to matching errors due to excessive scaling. If correct results are not found during feature matching, you can adjust this parameter, e.g., {scale: 1}.
// You can also specify {region: [...]} here to calculate features only for that region, improving efficiency.
let sceneFeatures = $images.detectAndComputeFeatures(capture);
// In the last match, we will draw the features and matches. This makes it easier to see the matching effect during debugging but increases time consumption.
let drawMatches = (i === n - 1 ? './matches.jpg' : undefined);
let result = $images.matchFeatures(sceneFeatures, objectFeatures, { drawMatches });
// Print results and center point. You can click using click(result.centerX, result.centerY).
console.log(result, result ? result.center : null);
// Recycle feature object
sceneFeatures.recycle();
if (drawMatches) {
// You can view the matches.jpg image in the current directory, which will draw detailed matching information.
app.viewFile('./matches.jpg');
}
}
// Recycle small image feature object
objectFeatures.recycle();
hellokitty.recycle();
```
--------------------------------
### ColorMapping findColor Example (Region and Threshold)
Source: http://autojs.cc/v8/images.html
Demonstrates finding a color within a specific region of the screen with a given similarity threshold.
```javascript
// 申请截图权限
$images.requestScreenCapture();
// 初始化ColorMapping
let ColorMapping = $colors.mapping;
// 创建ColorMapping实例
let cm = new ColorMapping();
// 截屏
let img = $images.captureScreen();
// 初始化颜色映射
cm.reset(img);
// 使用ColorMapping找色,指定找色区域为在位置(400, 500)的宽为300长为200的区域,指定找色临界值为4
let point = cm.findColor("#00ff00", {
region: [400, 500, 300, 200],
threshold: 4
});
if(point){
toast("找到啦:" + point);
}else{
toast("没找到");
}
// 释放ColorMapping
cm.recycle();
```
--------------------------------
### Click Event Example
Source: http://autojs.cc/v8/ui/basic.html
An example of how to attach a click event listener to a button and display a toast message.
```javascript
"ui";
$ui.layout(
);
$ui.click_me.on("click", () => {
toast("我被点啦");
});
```
--------------------------------
### $util.isBoolean Example 3
Source: http://autojs.cc/v8/util.html
Example showing `$util.isBoolean` returning true for `false`.
```javascript
$util.isBoolean(false);
// Returns: true
```
--------------------------------
### Get Intent Task Example
Source: http://autojs.cc/v8/timedTasks.html
Get an intent task by its ID. For example: Add a timed task that triggers when the phone's battery changes. Get this timed task by its ID. Log the path of the script that this timed task runs.
```javascript
// Add a timed task that triggers when the phone's battery changes
let id = $work_manager.addIntentTask({
path: "/sdcard/脚本/test.js",
action: Intent.ACTION_BATTERY_CHANGED,
delay: 0,
loopTimes: 1,
interval: 0
});
// Find this timed task by ID
let task = $work_manager.getIntentTask(id.id);
// Log the path of the script that this timed task runs
log(task.scriptPath);
```
--------------------------------
### Example: Launching a specific activity with root privileges
Source: http://autojs.cc/v8/app.html
This example shows how to use app.startActivity with root privileges to launch the Auto.js settings activity.
```javascript
app.startActivity({
packageName: "org.autojs.autojs",
className: "org.autojs.autojs.ui.settings.SettingsActivity_",
root: true
});
```
--------------------------------
### boundsInside Example
Source: http://autojs.cc/v8/automator/selector.html
Example of using boundsInside to find a TextView within the top half of the screen.
```javascript
var w = className("TextView").boundsInside(0, 0, device.width, device.height / 2).findOne();
log(w.text());
```
--------------------------------
### Get script directory
Source: http://autojs.cc/v8/engines.html
Example of getting the current working directory of a script.
```javascript
toast(engines.myEngine().cwd());
```
--------------------------------
### Example: Sending a text/plain broadcast with app.startActivity
Source: http://autojs.cc/v8/app.html
This example demonstrates using app.startActivity to send a broadcast with text/plain data.
```javascript
app.startActivity({
action: "SEND",
type: "text/plain",
data: "file:///sdcard/1.txt"
});
```
--------------------------------
### waitFor Example
Source: http://autojs.cc/v8/automator/selector.html
Example of using waitFor to block execution until a text element containing specific text appears.
```javascript
textContains("哈哈哈").waitFor();
```
--------------------------------
### findColorEquals Example
Source: http://autojs.cc/v8/images.html
Example of using findColorEquals to check for unread messages in QQ by looking for a specific red color.
```javascript
requestScreenCapture();
launchApp("QQ");
sleep(1200);
var p = findColorEquals(captureScreen(), "#f64d30");
if(p){
toast("有未读消息");
}else{
toast("没有未读消息");
}
```
--------------------------------
### Get current script engine's source
Source: http://autojs.cc/v8/engines.html
Example of getting the script source object for the current engine.
```javascript
log(engines.myEngine().getSource());
```
--------------------------------
### findOne with timeout Example
Source: http://autojs.cc/v8/automator/selector.html
Example of launching an app and finding a specific UI element within a timeout period, with fallback.
```javascript
//启动Auto.js
launchApp("Auto.js");
//在6秒内找出日志图标的控件
var w = id("action_log").findOne(6000);
//如果找到控件则点击
if(w != null){
w.click();
}else{
//否则提示没有找到
toast("没有找到日志图标");
}
```
--------------------------------
### findMultiColors with Region Example
Source: http://autojs.cc/v8/images.html
Example of using findMultiColors with a specified region to find multiple colors.
```javascript
var p = images.findMultiColors(img, "#123456", [[10, 20, "#ffffff"], [30, 40, "#000000"]], {
region: [0, 960, 1080, 960]
});
```
--------------------------------
### detectsMultiColors Example
Source: http://autojs.cc/v8/images.html
Example of using detectsMultiColors to check if multiple colors match at specified relative positions.
```javascript
log(images.detectsMultiColors(img, 100, 200, "#000000", [[3, 4, "#123456"], [8, 10, "#ff0000"]]));
```
--------------------------------
### app.getPackageName(appName)
Source: http://autojs.cc/v8/app.html
Gets the package name of an installed application by its app name.
```javascript
var name = getPackageName("QQ"); //返回"com.tencent.mobileqq"
```
--------------------------------
### Example: Converting an intent to a shell command
Source: http://autojs.cc/v8/app.html
This example demonstrates using app.intentToShell to convert an intent configuration into a shell command string for launching an activity.
```javascript
shell("am start " + app.intentToShell({
packageName: "org.autojs.autojs",
className: "org.autojs.autojs.ui.settings.SettingsActivity_"
}), true);
```
--------------------------------
### Find Color in Image (Loop Example)
Source: http://autojs.cc/v8/images.html
An example demonstrating a loop to continuously find a specific color (red) in the screen capture and report its coordinates.
```javascript
requestScreenCapture();
// Loop to find color, stop and report coordinates when red (#ff0000) is found
while(true){
var img = captureScreen();
var point = findColor(img, "#ff0000");
if(point){
toast("找到红色,坐标为(" + point.x + ", " + point.y + ")");
}
}
```
--------------------------------
### Find Circles Example
Source: http://autojs.cc/v8/images.html
An example demonstrating how to find circles in a captured screenshot using the `findCircles` function after converting the image to grayscale.
```javascript
// Request screenshot permission
requestScreenCapture();
// Capture screen
let img = captureScreen();
// Grayscale the image
let gray = images.grayscale(img);
// Find circles
let arr = findCircles(gray, {
dp: 1,
minDst: 80,
param1: 100,
param2: 100,
minRadius: 50,
maxRadius: 80,
});
// Recycle image
gray.recycle();
```
--------------------------------
### findImage Basic Example
Source: http://autojs.cc/v8/images.html
A simple example of using findImage to locate a template image within a larger image.
```javascript
var img = images.read("/sdcard/大图.png");
var templ = images.read("/sdcard/小图.png");
var p = findImage(img, templ);
if(p){
toast("找到啦:" + p);
}else{
toast("没找到");
}
```
--------------------------------
### Thread Control Example
Source: http://autojs.cc/v8/threads.html
You can get the status of a thread and control its execution through the Thread object returned by threads.start().
```javascript
var thread = threads.start(function(){
while(true){
log("子线程");
}
});
//停止线程执行
thread.interrupt();
```
--------------------------------
### detectsColor Example
Source: http://autojs.cc/v8/images.html
Example of using detectsColor to check if a Weibo post has been liked by examining the color of the like button's icon.
```javascript
requestScreenCapture();
// 找到点赞控件
var like = id("ly_feed_like_icon").findOne();
// 获取该控件中点坐标
var x = like.bounds().centerX();
var y = like.bounds().centerY();
// 截图
var img = captureScreen();
// 判断在该坐标的颜色是否为橙红色
if(images.detectsColor(img, "#fed9a8", x, y)){
// 是的话则已经是点赞过的了,不做任何动作
}else{
// 否则点击点赞按钮
like.click();
}
```
--------------------------------
### Find All Points for a Color
Source: http://autojs.cc/v8/images.html
Example of finding all points in an image that match a specific color.
```javascript
log(images.findAllPointsForColor(img, "#ffffff"));
```
--------------------------------
### findImage with Region Example
Source: http://autojs.cc/v8/images.html
A more complex example of using findImage with a specified region and threshold to find the WeChat icon on the desktop.
```javascript
auto();
requestScreenCapture();
var wx = images.read("/sdcard/微信图标.png");
// 返回桌面
home();
// 截图并找图
var p = findImage(captureScreen(), wx, {
region: [0, 50],
threshold: 0.8
});
if(p){
toast("在桌面找到了微信图标啦: " + p);
}else{
toast("在桌面没有找到微信图标");
}
```
--------------------------------
### Get all running script engines
Source: http://autojs.cc/v8/engines.html
Example of retrieving an array of all currently running script engines.
```javascript
log(engines.all());
```
--------------------------------
### Asynchronous Screen Capture with Event Listener
Source: http://autojs.cc/v8/images.html
Example of requesting asynchronous screen capture and listening for the 'screen_capture' event to process captured images.
```javascript
// Request screen capture permission, note the async: true parameter
requestScreenCapture({async: true});
let target = $images.read('./test.png');
$events.on('exit', () => target.recycle());
// Listen for screen capture
$images.on("screen_capture", capture => {
// Find image
let pos = $images.findImage(capture, target);
// Print
console.log(pos);
});
```
--------------------------------
### Request Screen Capture with Orientation
Source: http://autojs.cc/v8/images.html
Example of requesting screen capture with a specified orientation.
```javascript
requestScreenCapture({orientation: 0});
```
--------------------------------
### Get current engine's execution arguments
Source: http://autojs.cc/v8/engines.html
Example of accessing the execution arguments of the current script engine.
```javascript
log(engines.myEngine().execArgv);
```
--------------------------------
### MatchingResult.matches Example
Source: http://autojs.cc/v8/images.html
Iterates through the matches found by images.matchTemplate and logs the point and similarity of each match.
```javascript
var result = images.matchTemplate(img, template, {
max: 100
});
result.matches.forEach(match => {
log("point = " + match.point + ", similarity = " + match.similarity);
});
```
--------------------------------
### Padding Example
Source: http://autojs.cc/v8/ui/basic.html
Demonstrates how to set padding for a text view with different values for left, top, right, and bottom.
```javascript
"ui";
ui.layout(
);
```
--------------------------------
### RadioGroup getCheckedRadioButtonId Example
Source: http://autojs.cc/v8/ui/advanced.html
Shows how to get the ID of the currently checked radio button in a RadioGroup and retrieve its text and position.
```javascript
"ui";
$ui.layout(
);
$ui.get.on("click", () => {
// 获取radiogroup2勾选的单选框ID
let checkedId = $ui.radiogroup2.getCheckedRadioButtonId();
if (checkedId === -1) {
toastLog("没有任何单选框被勾选");
} else {
// 根据id获取勾选的radio
let checkedRadio = $ui.radiogroup2.findViewById(checkedId);
// 获取勾选的位置
let i = $ui.radiogroup2.indexOfChild(checkedRadio);
toastLog(
"当前勾选的单选框的文本: " +
checkedRadio.getText().toString() +
", 位置: " +
i
);
}
});
```
--------------------------------
### MatchingResult.sortBy Example
Source: http://autojs.cc/v8/images.html
Sorts the matching results by a specified criterion (e.g., 'top-right') and logs the sorted results.
```javascript
var result = images.matchTemplate(img, template, {
max: 100
});
log(result.sortBy("top-right"));
```
--------------------------------
### Image object recycling example
Source: http://autojs.cc/v8/images.html
Demonstrates how to read an image, perform operations, and then recycle the image object to free up memory.
```javascript
// 读取图片
var img = images.read("./1.png");
// 对图片进行操作
...
// 回收图片
img.recycle();
```
--------------------------------
### Save image with specified format and quality
Source: http://autojs.cc/v8/images.html
Example of saving an image with a specified format (JPEG) and quality (50%).
```javascript
// 把图片压缩为原来的一半质量并保存
var img = images.read("/sdcard/1.png");
images.save(img, "/sdcard/1.jpg", "jpg", 50);
app.viewFile("/sdcard/1.jpg");
```
--------------------------------
### threads.start() Example
Source: http://autojs.cc/v8/threads.html
Starts a new thread and executes the action. The main thread waits for all child threads to complete before stopping. If a child thread has an infinite loop, you may need to call exit() or threads.shutDownAll(). Threads started with threads.start() are automatically stopped when the script is forcefully stopped.
```javascript
threads.start(function(){
//在新线程执行的代码
while(true){
log("子线程");
}
});
while(true){
log("脚本主线程");
}
```
--------------------------------
### Find Color in a Specific Region
Source: http://autojs.cc/v8/images.html
Example of finding a color within a specified region of a local image with a given threshold.
```javascript
// Read local image /sdcard/1.png
var img = images.read("/sdcard/1.png");
// Check if image loaded successfully
if(!img){
toast("没有该图片");
exit();
}
// Find color in this image, specifying the search region as a 300x200 area at position (400, 500), with a threshold of 4
var point = findColor(img, "#00ff00", {
region: [400, 500, 300, 200],
threshold: 4
});
if(point){
toast("找到啦:" + point);
}else{
toast("没找到");
}
```
--------------------------------
### Thread.setTimeout() Example
Source: http://autojs.cc/v8/threads.html
Similar to timers.setTimeout(), but the timer executes within the specified thread. Throws IllegalStateException if the current thread has not started or has already finished execution.
```javascript
log("当前线程(主线程):" + threads.currentThread());
var thread = threads.start(function(){
//设置一个空的定时来保持线程的运行状态
setInterval(function(){}, 1000);
});
sleep(1000);
thread.setTimeout(function(){
log("当前线程(子线程):" + threads.currentThread());
exit();
}, 1000);
```
--------------------------------
### List all files and folders in sdcard directory
Source: http://autojs.cc/v8/files.html
This example demonstrates how to list all files and folders within the '/sdcard/' directory using the files.listDir function without any filter.
```javascript
var arr = files.listDir("/sdcard/");
log(arr);
```
--------------------------------
### once example
Source: http://autojs.cc/v8/events.html
Example of adding a listener that will be called only once.
```javascript
server.once('connection', (stream) => {
console.log('首次调用!');
});
```
--------------------------------
### Numeric Input Example
Source: http://autojs.cc/v8/ui/basic.html
Example of a numeric input field.
```xml
```
--------------------------------
### app.viewFile(path)
Source: http://autojs.cc/v8/app.html
Opens a file with another application.
```javascript
//查看文本文件
app.viewFile("/sdcard/1.txt");
```
--------------------------------
### quickSettings()
Source: http://autojs.cc/v8/keys.html
显示快速设置(下拉通知栏到底)。返回是否执行成功。 此函数依赖于无障碍服务。
```javascript
quickSettings()
```
--------------------------------
### idMatches Example
Source: http://autojs.cc/v8/automator/selector.html
Example of using idMatches with a regular expression.
```javascript
idMatches("[a-zA-Z]+")
```
--------------------------------
### RootAutomator2 Example
Source: http://autojs.cc/v8/coordinatesBasedAutomation.html
Demonstrates various operations of RootAutomator2 including tap, press, swipe, and multi-finger gestures (pinch-to-zoom). It shows how to use root or adb permissions and emphasizes the importance of flushing operations and exiting RootAutomator properly.
```javascript
let screenWidth = $device.width;
let screenHeight = $device.height;
// 使用root权限执行。也可以指定为\{adb: true\}使用adb权限,需要shizuku授权
const ra = new RootAutomator2(\{ root: true \});
// 点击(200, 200)的位置
ra.tap(200, 200);
sleep(1000);
// 按住屏幕中点持续500毫秒
ra.press(screenWidth / 2, screenHeight / 2, 500);
sleep(1000);
// 从(500, 200)滑动到(500, 1000),滑动时长300毫秒
ra.swipe(500, 200, 500, 1000, 300);
sleep(1000);
// 双指捏合
// 左上角位置
let p0 = {
x: screenWidth / 6,
y: screenHeight / 6,
};
// 右下角位置
let p1 = {
x: screenWidth - p0.x,
y: screenHeight - p0.y,
}
// 同时按下左上角和右下角,手指id为0和1
ra.touchDown([
\{ x: p0.x, y: p0.y, id: 0 \},
\{ x: p1.x, y: p1.y, id: 1 \},
]);
// 移动步数
const steps = 20;
// 计算每一步移动的偏移量
const stepX = Math.round((p1.x - p0.x) / steps) / 2;
const stepY = Math.round((p1.y - p0.y) / steps) / 2;
for (let i = 0; i < steps; i++) {
// 手指0向右下移动,手指1向左上移动
ra.touchMove([
\{ x: p0.x + stepX * i, y: p0.y + stepY * i, id: 0 \},
\{ x: p1.x - stepX * i, y: p1.y - stepY * i, id: 1 \}
]);
}
// 弹起所有手指
ra.touchUp();
// 等待前面的操作全部完成
ra.flush();
// 退出RootAutomator,如果没有正确退出,可能导致"手指"残留在屏幕上
ra.exit();
```