### Example: Click UI Element by Exact Bounds Source: https://docs.hamibot.com/reference/widgetsBasedAutomation Demonstrates how to use `bounds()` in conjunction with `clickable()` and `click()` to interact with a UI element based on its precise screen coordinates. This example targets a specific element on the QQ main interface, assuming its bounds are known. ```JavaScript bounds(951, 67, 1080, 196).clickable().click() ``` -------------------------------- ### Node.js util.inspect() Basic Usage Example Source: https://docs.hamibot.com/reference/util Shows a basic example of using `util.inspect()` to inspect the `util` object itself, demonstrating the `showHidden` and `depth` options for detailed output. ```JavaScript const util = require('util'); console.log(util.inspect(util, { showHidden: true, depth: null })); ``` -------------------------------- ### API Reference: `am start` Command Source: https://docs.hamibot.com/reference/shell Documents the `am start` command, used to launch an Activity specified by an intent. It lists various options like `-D` for debugging, `-W` to wait for completion, `--start-profiler` for profiling, `-R` for repeating launches, `-S` to force stop the target app, `--opengl-trace` for OpenGL tracing, and `--user` to specify the user. ```APIDOC am start [options] intent Launches an Activity specified by intent. Options: -D: Enable debugging. -W: Wait for launch to complete. --start-profiler file: Start profiler and send results to file. -P file: Similar to --start-profiler, but profiling stops when app becomes idle. -R count: Repeat Activity launch 'count' times. Top Activity will be finished before each repeat. -S: Force stop target app before launching Activity. --opengl-trace: Enable tracing of OpenGL functions. --user user_id | current: Specify user to run as; defaults to current user. ``` -------------------------------- ### API Reference: `am startservice` Command Source: https://docs.hamibot.com/reference/shell Documents the `am startservice` command, used to start a Service specified by an intent. It includes the `--user` option for specifying the user. ```APIDOC am startservice [options] intent Starts a Service specified by intent. Options: --user user_id | current: Specify user to run as; defaults to current user. ``` -------------------------------- ### Examples of util.format() Usage Source: https://docs.hamibot.com/reference/util Illustrates various use cases of `util.format()`, including partial placeholder replacement, handling excess arguments, and formatting non-string first arguments. ```JavaScript util.format('%s:%s', 'foo'); // Returns: 'foo:%s' ``` ```JavaScript util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz' ``` ```JavaScript util.format(1, 2, 3); // '1 2 3' ``` ```JavaScript util.format('%% %s'); // '%% %s' ``` -------------------------------- ### Hamibot API: Start Specific Hamibot Activity Source: https://docs.hamibot.com/reference/app This API allows Hamibot to launch its own specific internal interfaces, such as the console log view. The `name` parameter specifies which internal activity to start. ```APIDOC app.startActivity(name)\n name: 活动名称,可选的值为:\n console: 日志界面 ``` ```js app.startActivity('console'); ``` -------------------------------- ### JavaScript Example: Log Message (util.log) Source: https://docs.hamibot.com/reference/util Shows how to use `util.log` to print a timestamped message to the console. This method is deprecated and should be replaced by a third-party logging module. ```JavaScript const util = require('util'); util.log('Timestamped message.'); ``` -------------------------------- ### Click UI Element Using Bounds Coordinates (JavaScript) Source: https://docs.hamibot.com/reference/widgetsBasedAutomation This example shows how to interact with a UI element that might not be directly clickable. It finds an element by its description, gets its bounds, and then uses the `centerX()` and `centerY()` methods to calculate the center coordinates for a programmatic click. A root alternative using `Tap()` is also mentioned. ```JavaScript var b = desc('打开侧拉菜单').findOne().bounds(); click(b.centerX(), b.centerY()); //如果使用root权限,则用 Tap(b.centerX(), b.centerY()); ``` -------------------------------- ### Example: Find and Click Log Icon with Timeout Source: https://docs.hamibot.com/reference/widgetsBasedAutomation Demonstrates launching an app, then using `findOne(timeout)` to locate a UI element by its ID within a 6-second window. If the element is found, it is clicked; otherwise, a toast message is displayed indicating it was not found. ```JavaScript launchApp('Hamibot'); //Find the log icon control within 6 seconds var w = id('action_log').findOne(6000); //If the control is found, click it if (w != null) { w.click(); } else { //Otherwise, prompt that it was not found toast('Log icon not found'); } ``` -------------------------------- ### Node.js util.inherits() Example with EventEmitter Source: https://docs.hamibot.com/reference/util Demonstrates how to use `util.inherits()` to inherit prototype methods from `EventEmitter` in an ES5-style constructor function. Shows event emission and prototype chain verification. ```JavaScript const util = require('util'); const EventEmitter = require('events'); function MyStream() { EventEmitter.call(this); } util.inherits(MyStream, EventEmitter); MyStream.prototype.write = function(data) { this.emit('data', data); }; const stream = new MyStream(); console.log(stream instanceof EventEmitter); // true console.log(MyStream.super_ === EventEmitter); // true stream.on('data', (data) => { console.log(`Received data: "${data}"`); }); stream.write('It works!'); // Received data: "It works!" ``` -------------------------------- ### Monitor Shell Output with Callbacks Source: https://docs.hamibot.com/reference/shell Shows how to use `Shell.setCallback()` to listen for new output lines from the shell. This example sets up a callback to log each new line of output and then enters a loop to continuously accept and execute user commands until 'exit' is entered. ```JavaScript var sh = new Shell(); sh.setCallback({ onNewLine: function(line) { //有新的一行输出时打印到控制台 log(line); } }) while(true) { //循环输入命令 var cmd = dialogs.rawInput("请输入要执行的命令,输入exit退出"); if (cmd == "exit") { break; } //执行命令 sh.exec(cmd); } sh.exit(); ``` -------------------------------- ### Hamibot API: Send Email Source: https://docs.hamibot.com/reference/app This API allows Hamibot to compose and send an email by invoking an installed email application. It accepts an `options` object to specify recipients (to, cc, bcc), subject, body text, and an attachment path. All fields within the `options` object are optional. An `ActivityNotException` is thrown if no email application is installed on the device. ```APIDOC app.sendEmail(options)\n options: 发送邮件的参数。包括:\n email: | 收件人的邮件地址。如果有多个收件人,则用字符串数组表示\n cc: | 抄送收件人的邮件地址。如果有多个抄送收件人,则用字符串数组表示\n bcc: | 密送收件人的邮件地址。如果有多个密送收件人,则用字符串数组表示\n subject: 邮件主题(标题)\n text: 邮件正文\n attachment: 附件的路径。\nThrows: ActivityNotException (如果没有安装邮箱应用) ``` ```js // 发送邮件给 hamibot@example.com\napp.sendEmail({\n email: ['hamibot@example.com'],\n subject: '这是一个邮件标题',\n text: '这是邮件正文'\n}); ``` -------------------------------- ### Node.js ES6 Class Inheritance Example with EventEmitter Source: https://docs.hamibot.com/reference/util Illustrates modern JavaScript inheritance using `class` and `extends` keywords, achieving similar functionality to `util.inherits()` but with language-level support. Shows event emission. ```JavaScript const EventEmitter = require('events'); class MyStream extends EventEmitter { write(data) { this.emit('data', data); } } const stream = new MyStream(); stream.on('data', (data) => { console.log(`Received data: "${data}"`); }); stream.write('With ES6'); ``` -------------------------------- ### Log Light and Accelerometer Data to CSV Source: https://docs.hamibot.com/reference/sensors A comprehensive example demonstrating how to register 'light' and 'accelerometer' sensors with `sensors.delay.fastest`. It continuously collects data from both sensors and writes it to a CSV file every 0.5 seconds. The script automatically closes the file, unregisters all sensors, and opens the CSV file after 10 seconds. ```js //csv文件路径 const csvPath = "/storage/emulated/0/sensors_data.csv"; //记录光线传感器的数据 var light = 0; //记录加速度传感器的数据 var ax = 0; var ay = 0; var az = 0; //监听光线传感器 sensors.register("light", sensors.delay.fastest) .on("change", l => { light = l; }); //监听加速度传感器 sensors.register("accelerometer", sensors.delay.fastest) .on("change", (ax0, ay0, az0) => { ax = ax0; ay = ay0; az = az0; }); var file = open(csvPath, "w"); //写csv表格头 file.writeline("light,ax,ay,az") //每0.5秒获取一次数据并写入文件 setInterval(()=>{ file.writeline(util.format("%d,%d,%d,%d", light, ax, ay, az)); }, 500); //10秒后退出并打开文件 setTimeout(()=>{ file.close(); sensors.unregsiterAll(); app.viewFile(csvPath); }, 10 * 1000); ``` -------------------------------- ### Load JAR Files with runtime.loadJar Source: https://docs.hamibot.com/reference/globals Loads a target JAR file into the Hamibot runtime. Once loaded, classes from the JAR file can be used. The example demonstrates loading 'jsoup.jar' and then using 'org.jsoup.Jsoup' to parse an HTML file. ```APIDOC runtime.loadJar(path) * path Path to the JAR file ``` ```javascript // 加载jsoup.jar runtime.loadJar('./jsoup.jar'); // 使用jsoup解析html importClass(org.jsoup.Jsoup); log(Jsoup.parse(files.read('./test.html'))); ``` -------------------------------- ### Example: Scroll Hamibot Script List Source: https://docs.hamibot.com/reference/widgetsBasedAutomation Demonstrates how to find a scrollable `RecyclerView` and perform a forward scroll action. This is useful for navigating lists or content within the Hamibot application. ```JavaScript className('android.support.v7.widget.RecyclerView') .scrollable() .findOne() .scrollForward(); //或者classNameEndsWith("RecyclerView").scrollable().findOne().scrollForward(); ``` -------------------------------- ### Promisify Node.js Callback Functions with util.promisify Source: https://docs.hamibot.com/reference/util Shows how to convert a Node.js callback-style function (`fs.stat`) into a Promise-returning function using `util.promisify`. The example uses `.then()` and `.catch()` for promise handling. ```JavaScript const util = require('util'); const fs = require('fs'); const stat = util.promisify(fs.stat); stat('.').then((stats) => { // Do something with `stats` }).catch((error) => { // Handle the error. }); ``` -------------------------------- ### Example: Find Clickable Control at a Specific Point Source: https://docs.hamibot.com/reference/widgetsBasedAutomation Shows how to use `boundsContains()` to find a clickable control that includes a given point (500, 300). Once the control is found, it is then clicked. ```JavaScript var w = boundsContains(500, 300, 500, 300).clickable().findOne(); w.click(); ``` -------------------------------- ### Encode String to Uint8Array using TextEncoder in JavaScript Source: https://docs.hamibot.com/reference/util Demonstrates how to use the `TextEncoder` class to convert a string into a `Uint8Array`. This example initializes an encoder and then uses its `encode` method to process a sample string. ```JavaScript const encoder = new TextEncoder(); const uint8array = encoder.encode('this is some data'); ``` -------------------------------- ### Set Activity Content View (ui.setContentView) Source: https://docs.hamibot.com/reference/ui Sets a specified View object as the main content view for the current activity. This allows dynamic replacement or initial setup of the UI layout. ```APIDOC ui.setContentView(view) view: View - The view object to set ``` -------------------------------- ### Clicking Unclickable Widgets with Coordinates Source: https://docs.hamibot.com/reference/coordinatesBasedAutomation This example demonstrates how to click a UI widget that is not inherently clickable by obtaining its center coordinates and using the `click()` function. For devices with root access, `Tap` can be used as an alternative. ```JavaScript //获取这个控件 var widget = id('xxx').findOne(); //获取其中心位置并点击 click(widget.bounds().centerX(), widget.bounds().centerY()); //如果用root权限则用Tap ``` -------------------------------- ### Simulate Swipe with RootAutomator Source: https://docs.hamibot.com/reference/coordinatesBasedAutomation Simulates a swipe gesture from a start point (x1, y1) to an end point (x2, y2) using RootAutomator. An optional duration controls the swipe speed in milliseconds, and an ID supports multi-touch. ```APIDOC RootAutomator.swipe(x1, y1, x2, y2[, duration, id]) x1: Start X-coordinate y1: Start Y-coordinate x2: End X-coordinate y2: End Y-coordinate duration: Swipe duration in milliseconds (default 300) id: Multi-touch ID (optional, default 1) ``` -------------------------------- ### Hamibot API: Open URL in Browser Source: https://docs.hamibot.com/reference/app This API opens a specified URL in the device's default web browser. If the URL string does not begin with 'http://' or 'https://', 'http://' is automatically prepended. An `ActivityNotException` is thrown if no browser application is installed on the device. ```APIDOC app.openUrl(url)\n url: 网站的 Url,如果不以"http://"或"https://"开头则默认是"http://"。\nThrows: ActivityNotException (如果没有安装浏览器应用) ``` -------------------------------- ### API: Get All Development Scripts Source: https://docs.hamibot.com/rest/devscripts Retrieves a list of all development scripts associated with the authenticated user. Supports filtering by script name using a query parameter. Authentication is required via an 'Authorization' header. ```APIDOC GET /v1/devscripts Query Parameters: name: string (Optional) - Filter scripts by name. Example: /v1/devscripts?name=Demo Script Responses: 200 OK: Content-Type: application/json Body: { "count": 1, "items": [ { "_id": "bfe67d643ababe0ab6fda054", "name": "Demo Script" } ] } ``` ```JavaScript var res = http.request('https://api.hamibot.com/v1/devscripts', { method: 'GET', headers: { authorization: 'Your token (starts with hmp)' } }); log(res.body.json()); ``` ```Shell curl -H "Authorization: Your token (starts with hmp)" \ https://api.hamibot.com/v1/devscripts ``` -------------------------------- ### RootAutomator for High-Performance Touch Simulation Source: https://docs.hamibot.com/reference/coordinatesBasedAutomation RootAutomator is an object that enables touch and multi-touch simulations using root privileges, offering zero-delay execution. It's recommended to instantiate only one RootAutomator object per script and ensure it is properly exited, for example, by hooking into the script's exit event. ```APIDOC RootAutomator: An object for root-privileged touch simulation. ``` ```JavaScript var ra = new RootAutomator(); events.on('exit', function() { ra.exit(); }); //执行一些点击操作 ... ``` -------------------------------- ### Decode Byte Streams Incrementally with Node.js TextDecoder Source: https://docs.hamibot.com/reference/util This JavaScript example demonstrates how to use the `TextDecoder` class to incrementally decode a byte stream into a string. It initializes a decoder with a specific encoding and processes chunks of data, handling the end-of-stream to ensure all data is decoded. ```JavaScript const decoder = new TextDecoder('shift_jis'); let string = ''; let buffer; while (buffer = getNextChunkSomehow()) { string += decoder.decode(buffer, { stream: true }); } string += decoder.decode(); // end-of-stream ``` -------------------------------- ### Hamibot API: Uninstall Application Source: https://docs.hamibot.com/reference/app This API initiates the uninstallation process for an application specified by its package name. A system uninstall prompt will appear to the user. If the provided package name does not correspond to an installed application, the system's uninstaller will manage this, potentially displaying a 'not found' message. ```APIDOC app.uninstall(packageName)\n packageName: 应用包名 ``` ```js // 卸载 QQ\napp.uninstall('com.tencent.mobileqq'); ``` -------------------------------- ### Example: Find TextView within Top Half of Screen Source: https://docs.hamibot.com/reference/widgetsBasedAutomation Illustrates how to use `boundsInside()` to find a `TextView` control located within the top half of the device screen. It dynamically retrieves screen dimensions using `device.width` and `device.height` for flexible application. ```JavaScript var w = className('TextView') .boundsInside(0, 0, device.width, device.height / 2) .findOne(); log(w.text()); ``` -------------------------------- ### Hamibot API: View File Source: https://docs.hamibot.com/reference/app This API allows Hamibot to open a specified file using other applications installed on the device. The responsibility for handling non-existent files lies with the viewing application. If no suitable application is found to view the file, an `ActivityNotException` will be thrown. ```APIDOC app.viewFile(path)\n path: 文件路径\nThrows: ActivityNotException (如果找不出可以查看该文件的应用) ``` ```js // 查看文本文件\napp.viewFile('/storage/emulated/0/1.txt'); ``` -------------------------------- ### Retrieve Device Location (Longitude/Latitude) in JavaScript Source: https://docs.hamibot.com/reference/globals This JavaScript example demonstrates how to obtain the device's current longitude and latitude. It first requests 'access_fine_location' permission, then uses Android's LocationManager to get the last known location. It logs the device name, ID, and the retrieved coordinates. ```javascript const { ROBOT_ID } = hamibot.env; // https://docs.hamibot.com/reference/hamibot#env log('当前设备: ' + hamibot.robotName); log('设备 ID: ' + ROBOT_ID); // 请求位置权限 runtime.requestPermissions(['access_fine_location']); // https://docs.hamibot.com/reference/globals#runtime-requestpermissions-permissions let criteria = new android.location.Criteria(); criteria.setAccuracy(android.location.Criteria.ACCURACY_FINE); let locationManager = context.getSystemService( android.content.Context.LOCATION_SERVICE ); let provider = locationManager.getBestProvider(criteria, true); if (provider) { let location = locationManager.getLastKnownLocation(provider); if (location) { log('经度:' + location.getLongitude()); log('纬度:' + location.getLatitude()); } } hamibot.exit(); ``` -------------------------------- ### util.format() Method API Reference Source: https://docs.hamibot.com/reference/util Detailed API documentation for the `util.format()` method, explaining its `printf`-like formatting capabilities, supported placeholders, and behavior with varying numbers and types of arguments. ```APIDOC util.format(format[, ...args]) Added in: v0.5.3 Description: Returns a formatted string using the first argument as a printf-like format. Parameters: format: A printf-like format string containing placeholder tokens. ...args: Arguments to replace placeholders or append. Returns: A formatted string. Placeholders: %s: String %d: Number (integer or floating point) %i: Integer %f: Floating point value %j: JSON (replaces circular references with '[Circular]') %o: Object (generic JS object formatting, similar to util.inspect() with { showHidden: true, depth: 4, showProxy: true }) %O: Object (generic JS object formatting, similar to util.inspect() without options) %%: Single percent sign (does not consume an argument) Behavior: - If placeholder has no corresponding argument: Placeholder is not replaced. - If more arguments than placeholders: Extra arguments coerced to strings, concatenated with spaces. Objects/symbols inspected by util.inspect(). - If first argument is not a string: Concatenation of all arguments separated by spaces, each converted using util.inspect(). - If only one argument: Returned as is without formatting. ``` -------------------------------- ### TextDecoder Constructor API Reference Source: https://docs.hamibot.com/reference/util Documents the `TextDecoder` constructor, detailing its `encoding` and `options` parameters for initializing a text decoder instance. Explains how to specify encoding and control fatal decoding failures or BOM handling. ```APIDOC new TextDecoder([encoding[, options]]) encoding: Identifies the encoding. Defaults to 'utf-8'. options: fatal: true if decoding failures are fatal. Defaults to false. (Only when ICU is enabled) ignoreBOM: When true, includes BOM in result. When false, removes BOM. Defaults to false. (Only for 'utf-8', 'utf-16be', 'utf-16le') ``` -------------------------------- ### JavaScript Example: Check if Object is Undefined (util.isUndefined) Source: https://docs.hamibot.com/reference/util Demonstrates the usage of `util.isUndefined` with different values like numbers, `undefined`, and `null`. This method is deprecated. ```JavaScript const util = require('util'); const foo = undefined; util.isUndefined(5); // Returns: false util.isUndefined(foo); // Returns: true util.isUndefined(null); // Returns: false ``` -------------------------------- ### Register Gravity Sensor and Listen for Changes Source: https://docs.hamibot.com/reference/sensors Demonstrates how to register a 'gravity' sensor using `sensors.register`. It includes error handling for unsupported sensors and shows how to listen for 'change' events to log gravity acceleration data (gx, gy, gz). ```js //注册传感器监听 var sensor = sensors.register('gravity'); if (sensor == null) { toast('不支持重力传感器'); exit(); } //监听数据 sensor.on('change', (gx, gy, gz) => { log('重力加速度: %d, %d, %d', gx, gy, gz); }); ``` -------------------------------- ### JavaScript Example: Check if Object is String (util.isString) Source: https://docs.hamibot.com/reference/util Demonstrates the usage of `util.isString` to check various values, showing both string and non-string inputs. This method is deprecated. ```JavaScript const util = require('util'); util.isString(''); // Returns: true util.isString('foo'); // Returns: true util.isString(String('foo')); // Returns: true util.isString(5); // Returns: false ``` -------------------------------- ### API: Run a Development Script Source: https://docs.hamibot.com/rest/devscripts Initiates the execution of a specified development script on one or more devices. Requires the script ID and a list of target device IDs. Optional variables can be passed to the script. ```APIDOC POST /v1/devscripts/{devscript_id}/run Path Parameters: devscript_id: string (Required) - The unique ID of the development script to run. Request Body (application/json): devices: array (Required) - An array of device objects, each with an '_id' and 'name' to execute the script on. vars: object (Optional) - Script configuration variables, accessible via `hamibot.env` within the script. Responses: 204 No Content: Success 422 Unprocessable Entity: Parameter error ``` ```JavaScript http.request('https://api.hamibot.com/v1/devscripts/devscript_id/run', { method: 'POST', contentType: 'application/json', headers: { authorization: 'Your token (starts with hmp)' }, body: JSON.stringify({ devices: [{ _id: 'a51d237e9af41ecc021c9ff6', name: 'Unit Zero' }] }) }); ``` ```Shell curl \ -X POST \ -H "Authorization: Your token (starts with hmp)" \ -H "Content-Type: application/json" \ -d '{"devices": [{"_id": "a51d237e9af41ecc021c9ff6", "name": "Unit Zero"}]}' \ https://api.hamibot.com/v1/devscripts/devscript_id/run ``` -------------------------------- ### API: Get a Specific Development Script Source: https://docs.hamibot.com/rest/devscripts Retrieves details for a single development script by its unique ID. This endpoint provides specific information about a particular script. ```APIDOC GET /v1/devscripts/{devscript_id} Path Parameters: devscript_id: string (Required) - The unique ID of the development script. Responses: 200 OK: Content-Type: application/json Body: { "_id": "bfe67d643ababe0ab6fda054", "name": "Demo Script" } ``` ```JavaScript var res = http.request('https://api.hamibot.com/v1/devscripts/devscript_id', { method: 'GET', headers: { authorization: 'Your token (starts with hmp)' } }); log(res.body.json()); ``` ```Shell curl -H "Authorization: Your token (starts with hmp)" \ https://api.hamibot.com/v1/devscripts/devscript_id ``` -------------------------------- ### UiSelector.selected([b = true]) Method Source: https://docs.hamibot.com/reference/widgetsBasedAutomation Attaches a condition based on whether the control is currently selected. For example, a button might be 'selected' when its corresponding content is active or displayed. ```APIDOC UiSelector.selected([b = true]) b: - Indicates whether the control is selected (defaults to true). ``` -------------------------------- ### JavaScript Example: Check if Object is Symbol (util.isSymbol) Source: https://docs.hamibot.com/reference/util Demonstrates the usage of `util.isSymbol` to check various values, including numbers, strings, and actual Symbols. This method is deprecated. ```JavaScript const util = require('util'); util.isSymbol(5); // Returns: false util.isSymbol('foo'); // Returns: false util.isSymbol(Symbol('foo')); // Returns: true ``` -------------------------------- ### Enable Android Resources (ui.useAndroidResources) Source: https://docs.hamibot.com/reference/ui Activates the capability to use native Android resources like layouts, drawables, animations, and styles. This feature requires specific configuration in `project.json` to define the resource directory (`resDir`) and AndroidManifest file path, enabling more traditional Android UI development practices. ```APIDOC ui.useAndroidResources() ``` ```JSON { // ... "androidResources": { "resDir": "res", // 资源文件夹 "manifest": "AndroidManifest.xml" // AndroidManifest文件路径 } } ``` -------------------------------- ### Load DEX Files with runtime.loadDex Source: https://docs.hamibot.com/reference/globals Loads a target DEX file into the Hamibot runtime. Loading DEX files is faster than JAR files because JARs are internally converted to DEX before loading. The Android SDK's 'dx' tool can be used to convert JARs to DEX. ```APIDOC runtime.loadDex(path) * path Path to the DEX file ``` -------------------------------- ### UiObject Properties and Methods (APIDOC) Source: https://docs.hamibot.com/reference/widgetsBasedAutomation Documentation for core `UiObject` properties and methods, including how to retrieve element bounds, parent bounds, drawing order, ID, and text content. ```APIDOC bounds(): Rect Returns the screen bounds of the control as a Rect object. boundsInParent(): Rect Returns the bounds of the control within its parent control as a Rect object. drawingOrder(): Number Returns the drawing order of the control within its parent. Valid only for Android 7.0 and above; returns 0 for older versions. id(): String Gets the ID of the control. Returns null if the control has no ID. text(): String Gets the text content of the control. Returns "" if the control has no text. ``` -------------------------------- ### API Reference: `new Shell(root)` Constructor Source: https://docs.hamibot.com/reference/shell Documents the constructor for the `Shell` object, which creates a persistent shell process. It explains the `root` parameter, which determines if the shell process runs with root permissions and affects subsequent commands executed by this object. ```APIDOC new Shell(root) root: Whether to run a shell process with root permissions (default: false) ``` -------------------------------- ### Sensors Module API Reference Source: https://docs.hamibot.com/reference/sensors Detailed API documentation for the `sensors` module, outlining the various sensor types available and the parameters passed to their `on('change', ...)` event listeners. Each sensor's entry specifies the event object and specific data parameters. ```APIDOC sensors: register(sensorType: string): SensorListener unregister(sensorType: string): void SensorListener: on(eventName: 'change', callback: function): void Callback Parameters by Sensor Type: accelerometer: (event: SensorEvent, ax: Number, ay: Number, az: Number) event: SensorEvent - Sensor event object with all information. ax: Number - x-axis acceleration (m/s^2) ay: Number - y-axis acceleration (m/s^2) az: Number - z-axis acceleration (m/s^2) orientation: (event: SensorEvent, azimuth: Number, pitch: Number, roll: Number) event: SensorEvent - Sensor event object with all information. azimuth: Number - Azimuth angle (0-359 degrees) pitch: Number - Pitch angle (-180-180 degrees) roll: Number - Roll angle (-90-90 degrees) gyroscope: (event: SensorEvent, wx: Number, wy: Number, wz: Number) event: SensorEvent - Sensor event object with all information. wx: Number - x-axis angular velocity (rad/s) wy: Number - y-axis angular velocity (rad/s) wz: Number - z-axis angular velocity (rad/s) magnetic_field: (event: SensorEvent, bx: Number, by: Number, bz: Number) event: SensorEvent - Sensor event object with all information. bx: Number - x-axis magnetic field strength (uT) by: Number - y-axis magnetic field strength (uT) bz: Number - z-axis magnetic field strength (uT) gravity: (event: SensorEvent, gx: Number, gy: Number, gz: Number) event: SensorEvent - Sensor event object with all information. gx: Number - x-axis gravitational acceleration (m/s^2) gy: Number - y-axis gravitational acceleration (m/s^2) gz: Number - z-axis gravitational acceleration (m/s^2) linear_acceleration: (event: SensorEvent, ax: Number, ay: Number, az: Number) event: SensorEvent - Sensor event object with all information. ax: Number - x-axis linear acceleration (m/s^2) ay: Number - y-axis linear acceleration (m/s^2) az: Number - z-axis linear acceleration (m/s^2) ambient_temperature: (event: SensorEvent, t: Number) event: SensorEvent - Sensor event object with all information. t: Number - Ambient temperature (Celsius) light: (event: SensorEvent, light: Number) event: SensorEvent - Sensor event object with all information. light: Number - Ambient light intensity (lux) pressure: (event: SensorEvent, p: Number) event: SensorEvent - Sensor event object with all information. p: Number - Atmospheric pressure (hPa) proximity: (event: SensorEvent, distance: Number) event: SensorEvent - Sensor event object with all information. distance: Number - Distance to obstacle (0 for near, 5 for far/no obstacle) relative_humidity: (event: SensorEvent, rh: Number) event: SensorEvent - Sensor event object with all information. rh: Number - Relative humidity (0-100%) ``` -------------------------------- ### Node.js util.inspect() API Reference Source: https://docs.hamibot.com/reference/util Detailed documentation for the `util.inspect()` method, used for debugging objects. Includes parameters, options like `showHidden`, `depth`, `colors`, and `maxArrayLength`, along with historical changes. ```APIDOC util.inspect(object[, options]) History: v6.6.0: Custom inspection functions can now return `this`. v6.3.0: The `breakLength` option is supported now. v6.1.0: The `maxArrayLength` option is supported now; in particular, long arrays are truncated by default. v6.1.0: The `showProxy` option is supported now. v0.3.0: Added in v0.3.0. Parameters: object: - Any JavaScript primitive or Object. options: showHidden: - If `true`, the `object`'s non-enumerable symbols and properties will be included. Defaults to `false`. depth: - Specifies the number of times to recurse. Defaults to `2`. `null` for indefinite. colors: - If `true`, the output will be styled with ANSI color codes. Defaults to `false`. customInspect: - If `false`, custom `inspect(depth, opts)` functions on the `object` will not be called. Defaults to `true`. showProxy: - If `true`, `Proxy` objects will show their `target` and `handler` objects. Defaults to `false`. maxArrayLength: - Max array/TypedArray elements to include. Defaults to `100`. `null` for all, `0` or negative for none. breakLength: - The length at which an object's keys are split across multiple lines. Defaults to `60`. `Infinity` for single line. Returns: - A string representation of `object` that is primarily useful for debugging. Custom `inspect(depth, opts)` functions: Values may supply their own custom `inspect(depth, opts)` functions, receiving `depth` and `opts`. ``` -------------------------------- ### Check if Object is Boolean using util.isBoolean() in JavaScript Source: https://docs.hamibot.com/reference/util Demonstrates the usage of the deprecated `util.isBoolean()` method to check if a value is a boolean. This example provides various inputs to show which values return true or false. ```JavaScript const util = require('util'); util.isBoolean(1); // Returns: false util.isBoolean(0); // Returns: false util.isBoolean(false); // Returns: true ``` -------------------------------- ### Initialize and Use Persistent Shell Object Source: https://docs.hamibot.com/reference/shell Illustrates the creation of a new `Shell` object for persistent command execution, demonstrating how to execute a command like force-stopping an application and then properly exit the shell session. This approach is more efficient for multiple commands than repeated calls to `shell()`. ```JavaScript var sh = new Shell(true); //强制停止微信 sh.exec("am force-stop com.tencent.mm"); sh.exit(); ``` -------------------------------- ### util.deprecate() Method API Reference Source: https://docs.hamibot.com/reference/util Detailed API documentation for the `util.deprecate()` method, explaining its parameters, behavior, and interaction with command-line flags and `process` properties for warning control. ```APIDOC util.deprecate(function, string) Added in: v0.8.0 Description: Wraps a function or class, marking it as deprecated. Parameters: function: The function or class to deprecate. string: The deprecation message. Returns: A new function. Behavior: - Emits a DeprecationWarning via process.on('warning') event. - Warning is emitted and printed to stderr exactly once by default. - Wrapped function is called after warning. Warning Control: - Suppress warnings: --no-deprecation, --no-warnings, process.noDeprecation = true (prior to first warning). - Trace warnings: --trace-deprecation, --trace-warnings, process.traceDeprecation = true (prints warning and stack trace). - Throw exception: --throw-deprecation, process.throwDeprecation = true (throws exception). Precedence: --throw-deprecation / process.throwDeprecation takes precedence over trace flags. ``` -------------------------------- ### Register and Listen to Light Sensor Source: https://docs.hamibot.com/reference/sensors This snippet demonstrates how to register a listener for the light sensor and log its current intensity when it changes. The `on('change', ...)` method is used to specify the callback function, which receives the event object and the light intensity value. ```JavaScript //光线传感器监听 sensors.register('light').on('change', (event, light) => { log('当前光强度为', light); }); ``` -------------------------------- ### API Reference: `Shell.setCallback(callback)` Method Source: https://docs.hamibot.com/reference/shell Documents the `Shell.setCallback` method, which allows setting a callback object to listen for shell output. It details the `onOutput` and `onNewLine` properties of the callback object, explaining their parameters and when they are invoked. ```APIDOC Shell.setCallback(callback) callback: Callback functions onOutput: Called when new shell output is available (parameter: output) onNewLine: Called when a new line of output is available (parameter: line, without newline character) Returns: ``` -------------------------------- ### Check if Object is Array using util.isArray() in JavaScript Source: https://docs.hamibot.com/reference/util Illustrates the usage of the deprecated `util.isArray()` method to determine if a given object is an array. This example shows its behavior with various inputs, including empty arrays and plain objects. ```JavaScript const util = require('util'); util.isArray([]); // Returns: true util.isArray(new Array()); // Returns: true util.isArray({}); // Returns: false ``` -------------------------------- ### API Reference: util.puts Method Source: https://docs.hamibot.com/reference/util Documents the `util.puts` method, a deprecated predecessor of `console.log()`. ```APIDOC util.puts([...strings]) Added in: v0.3.0 Deprecated since: v0.11.3 Stability: 0 - Deprecated: Use console.log() instead. Description: Deprecated predecessor of console.log. ``` -------------------------------- ### Get and Display UI Element Bounds (JavaScript) Source: https://docs.hamibot.com/reference/widgetsBasedAutomation This snippet demonstrates how to find a UI element by its text content, retrieve its screen bounds using `bounds()`, and display these bounds as a toast message. It's useful for debugging element positions. ```JavaScript var b = text('Hamibot').findOne().bounds(); toast('控件在屏幕上的范围为' + b); ``` -------------------------------- ### API: Create a New Development Script Source: https://docs.hamibot.com/rest/devscripts Creates a new development script entry. A name for the new script is required. The API returns the ID and name of the newly created script. ```APIDOC POST /v1/devscripts Request Body (application/json): name: string (Required) - The desired name for the new script. Responses: 201 Created: Content-Type: application/json Body: { "_id": "bfe67d643ababe0116fda052", "name": "Unnamed9527" } ``` ```JavaScript var res = http.request('https://api.hamibot.com/v1/devscripts', { method: 'POST', headers: { authorization: 'Your token (starts with hmp)' }, body: JSON.stringify({ name: 'script name' }) }); log(res.body.json()); ``` ```Shell curl \ -X POST \ -H "Authorization: Your token (starts with hmp)" \ -d '{"name": "script name"}' \ https://api.hamibot.com/v1/devscripts ``` -------------------------------- ### API Reference: Android `am` Command Overview Source: https://docs.hamibot.com/reference/shell Provides an overview of the Android `am` (Activity Manager) command, used for managing application activities and services. It notes that these commands are executed via `shell('am ...')`. ```APIDOC am Command (Activity Manager) Used to manage application activities, services, etc. All commands start with "am ". Example: shell('am start -p com.tencent.mm'); (Starts WeChat) ``` -------------------------------- ### API Reference: `shell(cmd[, root])` Function Source: https://docs.hamibot.com/reference/shell Documents the `shell` function, which executes a single command and returns its result. It details the `cmd` and `root` parameters, and describes the structure of the returned object including `code`, `result`, and `error` properties. ```APIDOC shell(cmd[, root]) cmd: Command to execute root: Whether to run with root permissions (default: false) Returns: code: Return code (0 for success, non-zero for failure) result: Standard output (stdout) error: Standard error (stderr) ``` -------------------------------- ### Check if Current Thread is UI Thread (ui.isUiThread) Source: https://docs.hamibot.com/reference/ui Determines if the currently executing thread is the main UI thread. This function is essential for ensuring UI operations are performed safely on the correct thread. The example demonstrates its behavior in both the main thread and a background thread. ```APIDOC ui.isUiThread() Returns: Boolean ``` ```JavaScript 'ui'; log(ui.isUiThread()); // => true $threads.start(function () { log(ui.isUiThread()); // => false }); ```