### Structured Logging Example in AutoX.js Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt This example demonstrates structured logging within the AutoX.js console, combining various logging methods, timing operations, and event listeners for a robust logging output. It includes setting a custom console title, logging script start and completion times, and recording script information. Dependencies include the AutoX.js environment. ```javascript // Example: Structured logging console.show(); console.setTitle("Automation Log", "#ff00aa00", 35); console.info("=== Script Started ==="); console.log("User: Administrator"); console.log("Time: " + new Date().toLocaleString()); console.warn("Running in test mode"); console.time("execution"); // ... script operations ... console.timeEnd("execution"); console.info("=== Script Completed ==="); ``` -------------------------------- ### Handle WebView Loading and Button Clicks Source: https://github.com/nakanosanku/autoxv6doc/blob/main/docs/rhino/advanced/webViewAndHtml.md Handles user interactions with UI elements, specifically buttons, to control WebView behavior. This includes initiating a web page load upon clicking 'surfInternetBtn' and 'loadLocalHtmlBtn', and starting a 'console' activity when 'consoleBtn' is clicked. It utilizes the previously defined `webViewExpand_init` function. ```JavaScript webViewExpand_init(ui.webView); ui.webView.loadUrl("https://wht.im"); ui.surfInternetBtn.on("click", () => { webViewExpand_init(ui.webView); ui.webView.loadUrl("https://wht.im"); }); ui.consoleBtn.on("click", () => { app.startActivity("console"); }); ui.loadLocalHtmlBtn.on("click", () => { webViewExpand_init(ui.webView); let path = "file:" + files.path("game.html"); ui.webView.loadUrl(path); }); ``` ``` -------------------------------- ### Complete Image Processing Pipeline - JavaScript Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt An example demonstrating a sequence of image processing operations: cropping, resizing, converting to grayscale, and saving with compression. Proper recycling of all intermediate and final image objects is crucial. ```javascript // Complete image processing pipeline var original = images.read("/sdcard/input.jpg"); if (original) { console.log("Original size: " + original.getWidth() + "x" + original.getHeight()); // 1. Crop to region of interest var cropped = images.clip(original, 50, 50, 500, 500); // 2. Resize to standard size var resized = images.resize(cropped, [300, 300]); // 3. Convert to grayscale var gray = images.grayscale(resized); // 4. Save with compression images.save(gray, "/sdcard/processed.jpg", "jpeg", 70); // Clean up original.recycle(); cropped.recycle(); resized.recycle(); gray.recycle(); toast("Image processing complete"); } ``` -------------------------------- ### JavaScript - Get Device Info, Control Settings, and Perform Operations Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt This JavaScript code snippet demonstrates how to retrieve various device properties such as screen dimensions, brand, model, Android version, IMEI, Android ID, and MAC address. It also covers controlling screen brightness and mode, adjusting media, notification, and alarm volumes, checking battery status, managing memory information, controlling the screen state (on/off, wake up, keep screen on), initiating and canceling vibrations, detecting navigation bars, and includes an example of automated brightness adjustment based on time. Requires system settings permissions for brightness and volume control. ```javascript // Get screen dimensions log("Screen width: " + device.width); log("Screen height: " + device.height); // Get device information log("Device brand: " + device.brand); // e.g., "Xiaomi", "Huawei" log("Device model: " + device.model); log("Android version: " + device.release); // e.g., "10", "11" log("SDK version: " + device.sdkInt); // e.g., 29, 30 log("IMEI: " + device.getIMEI()); log("Android ID: " + device.getAndroidId()); log("MAC address: " + device.getMacAddress()); // Screen brightness control (requires system settings permission) var currentBrightness = device.getBrightness(); // 0-255 log("Current brightness: " + currentBrightness); device.setBrightness(128); // Set to 50% brightness // Brightness mode var brightnessMode = device.getBrightnessMode(); // 0=manual, 1=auto log("Brightness mode: " + brightnessMode); device.setBrightnessMode(0); // Set to manual mode // Volume control (requires system settings permission) var musicVolume = device.getMusicVolume(); var maxVolume = device.getMusicMaxVolume(); log("Music volume: " + musicVolume + "/" + maxVolume); device.setMusicVolume(10); // Set media volume var notificationVolume = device.getNotificationVolume(); device.setNotificationVolume(5); var alarmVolume = device.getAlarmVolume(); device.setAlarmVolume(8); // Battery information var battery = device.getBattery(); // Returns 0.0-100.0 log("Battery level: " + battery + "% "); var charging = device.isCharging(); log("Charging: " + charging); // Memory information var totalMem = device.getTotalMem(); // Total memory in bytes var availMem = device.getAvailMem(); // Available memory in bytes log("Memory: " + (availMem / 1024 / 1024).toFixed(2) + " MB / " + (totalMem / 1024 / 1024).toFixed(2) + " MB"); // Screen state if (device.isScreenOn()) { log("Screen is on"); } else { log("Screen is off"); } // Wake up device device.wakeUp(); // Turn on screen device.wakeUpIfNeeded(); // Only wake if screen is off // Keep screen on device.keepScreenOn(); // Keep screen on indefinitely device.keepScreenOn(3600 * 1000); // Keep on for 1 hour device.keepScreenDim(1800 * 1000); // Keep on but allow dimming for 30 min device.cancelKeepingAwake(); // Cancel keep-awake // Vibration device.vibrate(1000); // Vibrate for 1 second device.vibrate(2000); // Vibrate for 2 seconds device.cancelVibration(); // Stop vibration // Navigation bar detection if (device.checkDeviceHasNavigationBar()) { var navBarHeight = device.getVirtualBarHeigh(); log("Navigation bar height: " + navBarHeight + "px"); // Calculate clickable area: device.height - navBarHeight } // Example: Automated brightness adjustment based on time var hour = new Date().getHours(); if (hour >= 22 || hour < 6) { // Night time: dim screen device.setBrightnessMode(0); device.setBrightness(50); } else { // Day time: normal brightness device.setBrightnessMode(1); // Auto brightness } ``` -------------------------------- ### HTTP Network Requests API Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt APIs for performing HTTP requests, including GET and POST operations with support for custom headers, JSON, and file uploads. ```APIDOC ## HTTP Network Requests API ### Description APIs for making HTTP requests. Supports GET, POST, and other methods with full control over headers, request body (JSON, form data, multipart), and asynchronous execution. ### Methods - **http.get(url, [options], [callback])**: Performs an HTTP GET request. - **http.post(url, [data], [options], [callback])**: Performs an HTTP POST request with form data. - **http.postJson(url, [json], [options], [callback])**: Performs an HTTP POST request with JSON data. - **http.postMultipart(url, [data], [options], [callback])**: Performs an HTTP POST request with multipart/form-data, typically for file uploads. ### Parameters #### Common Options for Requests - **headers** (object): Custom HTTP headers to send with the request. - **timeout** (number): Request timeout in milliseconds. #### Request Body (POST methods) - **data** (object): Key-value pairs for form data. - **json** (object): JSON object to send as the request body. - **file** (File object): File to upload in multipart requests. #### Callback Function (for asynchronous requests) - **res** (object): The response object. - **err** (Error): An error object if the request failed. ### Request Example (JavaScript) ```javascript // Simple GET request var response = http.get("www.baidu.com"); console.log("Status Code: " + response.statusCode); console.log("HTML Content: " + response.body.string()); // POST JSON data to API var apiUrl = "http://api.example.com/data"; var response = http.postJson(apiUrl, { key: "api_key_123", info: "Hello API", userid: "user001" }); console.log("API Response: " + response.body.string()); // Asynchronous GET request http.get("www.example.com", {}, function(res, err) { if (err) { console.error(err); return; } console.log("Async response code: " + res.statusCode); }); ``` ### Response - **Success Response (200)**: - **statusCode** (number): The HTTP status code of the response. - **headers** (object): An object containing the response headers. - **body** (object): An object representing the response body, with methods like `string()`, `json()`, `bytes()`. #### Response Example (JSON) ```json { "statusCode": 200, "headers": { "Content-Type": "application/json" }, "body": { "status": "success", "data": { "temperature": "25°C", "humidity": "60%" } } } ``` #### Error Handling - Errors during the request (e.g., network issues, timeouts) will be passed to the callback function as an `Error` object. ``` -------------------------------- ### Application Management - Launch, Control, and Interact with Apps Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt Manage applications by launching them by name or package, accessing settings, opening files with external apps, and sending intents for inter-app communication. This includes functions to get package names, app names, uninstall apps, and open specific URLs or files. ```javascript // Launch WeChat by package name launch("com.tencent.mm"); // Launch app by display namelaunchApp("Auto.js"); // Get package name from app name var qqPackage = app.getPackageName("QQ"); // Returns "com.tencent.mobileqq" // Get app name from package var appName = app.getAppName("com.tencent.mobileqq"); // Returns "QQ" // Open app settings page app.openAppSetting("com.tencent.mm"); // Open URL in browser app.openUrl("https://www.autojs.org"); // View file with appropriate app app.viewFile("/sdcard/document.txt"); // Edit file with external editor app.editFile("/sdcard/script.js"); // Send email with attachments app.sendEmail({ email: ["user@example.com", "admin@example.com"], subject: "Automation Report", text: "Script execution completed successfully", attachment: "/sdcard/report.pdf" }); // Advanced: Open QQ chat window using intent var qq = "123456789"; app.startActivity({ action: "android.intent.action.VIEW", data: "mqq://im/chat?chat_type=wpa&version=1&src_type=web&uin=" + qq, packageName: "com.tencent.mobileqq" }); // Uninstall application app.uninstall("com.example.app"); ``` -------------------------------- ### HTTP Network Requests - GET and POST Operations Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt Perform HTTP requests including GET and POST methods with full control over headers. Supports JSON data, form data, and multipart file uploads. Both synchronous and asynchronous execution are available, along with JSON parsing and response header access. ```javascript // Simple GET request console.show(); var response = http.get("www.baidu.com"); log("Status Code: " + response.statusCode); log("HTML Content: " + response.body.string()); // GET request with custom headers var r = http.get("www.example.com", { headers: { "Accept-Language": "zh-cn,zh;q=0.5", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11" } }); log("Response: " + r.body.string()); // GET weather data and parse JSON var city = "广州"; var res = http.get("http://www.sojson.com/open/api/weather/json.shtml?city=" + city); if (res.statusCode != 200) { toast("Request failed: " + res.statusCode + " " + res.statusMessage); } else { var weather = res.body.json(); toast(util.format("温度: %s 湿度: %s 空气质量: %s", weather.data.wendu, weather.data.shidu, weather.quality)); } // POST form data (simulating login) var url = "https://login.example.com/login"; var username = "myuser"; var password = "mypass"; var res = http.post(url, { username: username, password: password }); if (res.body.string().contains("success")) { toast("Login successful"); } else { toast("Login failed"); } // POST JSON data to API var apiUrl = "http://api.example.com/data"; var response = http.postJson(apiUrl, { key: "api_key_123", info: "Hello API", userid: "user001" }); log("API Response: " + response.body.string()); // Upload file with multipart/form-data var uploadRes = http.postMultipart("http://example.com/upload", { appId: "app123", file: open("/sdcard/document.txt") }); log("Upload result: " + uploadRes.body.string()); // Asynchronous GET request with callback http.get("www.example.com", {}, function(res, err) { if (err) { console.error(err); return; } log("Async response code: " + res.statusCode); log("Async content: " + res.body.string()); }); // Access response headers var res = http.get("www.qq.com"); console.log("HTTP Headers:"); for (var headerName in res.headers) { console.log("%s: %s", headerName, res.headers[headerName]); } ``` -------------------------------- ### Get File Information - JavaScript Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt Extracts specific information about a file, such as its name, name without the extension, and file extension. This is helpful for file processing and organization. ```javascript // Get file information var name = files.getName("/sdcard/documents/report.pdf"); // "report.pdf" var nameNoExt = files.getNameWithoutExtension("/sdcard/report.pdf"); // "report" var ext = files.getExtension("/sdcard/photo.jpg"); // "jpg" ``` -------------------------------- ### Get Special Paths - JavaScript Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt Retrieves important system-defined paths, including the path to the external storage (SD card), the current working directory of the script, and converts relative paths to absolute paths. ```javascript // Get special paths var sdcard = files.getSdcardPath(); // External storage path var scriptDir = files.cwd(); // Current script directory var absolutePath = files.path("./data.json"); // Relative to absolute path ``` -------------------------------- ### Initialize and Configure WebView in Android Source: https://github.com/nakanosanku/autoxv6doc/blob/main/docs/rhino/advanced/webViewAndHtml.md Initializes and configures a WebView component in Android, setting up various clients for handling navigation, errors, and console messages. It also includes logic for loading URLs and handling potential exceptions like ActivityNotFoundException. Dependencies include Android's WebView and related classes. ```JavaScript function webViewExpand_init(webView) { webView.setWebViewClient(new JavaAdapter(android.webkit.WebViewClient, { shouldOverrideUrlLoading: (view, url) => { try { if (new RegExp('^https?://').test(url)) { view.loadUrl(url); } else { let i = new android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(url)); view.getContext().startActivity(i); } } catch (e) { if (e instanceof android.content.ActivityNotFoundException) { webView.loadUrl(url); } else { toastLog("无法打开URL: " + url); } console.trace(e); } return true; }, onReceivedError: (webView, webResourceRequest, webResourceError) => { let url = webResourceRequest.getUrl(); let errorCode = webResourceError.getErrorCode(); let description = webResourceError.getDescription(); console.trace(errorCode + " " + description + " " + url); }, })); webView.setWebChromeClient(new JavaAdapter(android.webkit.WebChromeClient, { onConsoleMessage: (msg) => { console.log( "[%s:%s]: %s", msg.sourceId(), msg.lineNumber(), msg.message() ); }, } )); } ``` -------------------------------- ### Create Files and Directories - JavaScript Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt This snippet demonstrates how to create new files and directories. `files.create()` creates a file or directory if it doesn't exist, while `files.createWithDirs()` ensures that parent directories are also created if they are missing. ```javascript // Create file or directory files.create("/sdcard/NewFolder/"); files.createWithDirs("/sdcard/Parent/Child/file.txt"); // Creates parent dirs ``` -------------------------------- ### Application Management API Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt APIs for launching, controlling, and managing applications on Android devices. ```APIDOC ## Application Management API ### Description APIs for launching, controlling, and managing applications on Android devices. This includes launching apps by name or package, managing app settings, opening files, and sending intents. ### Methods - **launch(packageNameOrAppName)**: Launches an application by its package name or display name. - **launchApp(appName)**: Launches an application by its display name. - **app.getPackageName(appName)**: Gets the package name of an application from its display name. - **app.getAppName(packageName)**: Gets the display name of an application from its package name. - **app.openAppSetting(packageName)**: Opens the settings page for a specific application. - **app.openUrl(url)**: Opens a given URL in the default browser. - **app.viewFile(filePath)**: Opens a file with the appropriate application. - **app.editFile(filePath)**: Opens a file for editing with an external editor. - **app.sendEmail(options)**: Sends an email with specified recipients, subject, text, and attachments. - **app.startActivity(options)**: Starts a new Android activity with specified action, data, and package name. - **app.uninstall(packageName)**: Uninstalls a specified application. ### Request Example (JavaScript) ```javascript // Launch WeChat by package name launch("com.tencent.mm"); // Launch app by display name launchApp("Auto.js"); // Send email app.sendEmail({ email: ["user@example.com"], subject: "Automation Report", text: "Script execution completed successfully", attachment: "/sdcard/report.pdf" }); ``` ### Response - **Success**: Varies depending on the method. Most methods do not return a value directly but perform an action. - **Error**: May throw exceptions for invalid parameters or unsuccessful operations. ``` -------------------------------- ### Console Logging and Control in AutoX.js Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt This snippet demonstrates how to manage the console window (show, hide, clear), log messages with different levels (verbose, info, warn, error), perform assertions, and time code execution. It covers basic logging, formatted output, and the use of the global 'log' function. Dependencies include the AutoX.js environment. ```javascript // Show console window (requires floating window permission) console.show(); console.show(true); // Auto-hide when script ends // Hide console console.hide(); // Clear console console.clear(); // Basic logging console.log("Basic log message"); log("Global log function"); // Same as console.log // Formatted logging with multiple parameters const count = 5; console.log("count: %d", count); console.log("count:", count); // Different log levels with color coding console.verbose("Verbose message"); // Gray text console.info("Important information"); // Green text console.warn("Warning message"); // Blue text console.error("Error occurred"); // Red text // Assertion var result = 1 + 1; console.assert(result == 2, "Math error!"); // console.assert(result == 3, "This will fail"); // Script stops // Performance timing console.time("calculation"); var sum = 0; for (let i = 0; i < 100000; i++) { sum += i; } console.timeEnd("calculation"); // Prints: calculation: XXX ms // Multiple timers console.time("operation1"); console.time("operation2"); sleep(1000); console.timeEnd("operation1"); sleep(500); console.timeEnd("operation2"); // Stack trace function functionA() { functionB(); } function functionB() { console.trace("Trace point"); } functionA(); // Prints call stack ``` -------------------------------- ### User Input and Console Customization in AutoX.js Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt This snippet illustrates how to interact with the user via the console by capturing raw text input and evaluated input. It also details how to customize the appearance and behavior of the floating console window, including title, size, position, font size, background, and input enablement. Dependencies include the AutoX.js environment and device information. ```javascript // User input from console console.show(); var name = console.rawInput("Enter your name:"); tOast("Hello, " + name); var age = console.input("Enter your age:"); // Input "25" - evaluates as number tOast("Next year you will be " + (age + 1)); // Customize console appearance console.show(); console.setTitle("My Script Console", "#ff0000ff", 40); // Blue title, 40dp height console.setSize(device.width / 2, device.height / 2); // Half screen size console.setPosition(100, 100); // Position at (100, 100) console.setLogSize(16); // Font size 16dp console.setBackgroud("#aa000000"); // Semi-transparent black background console.setMaxLines(500); // Limit to 500 lines console.setCanInput(false); // Disable input ``` -------------------------------- ### File Logging and Event Handling in AutoX.js Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt This snippet shows how to configure global console settings to log output to a file and how to listen for console events, such as 'println' for all log messages and 'ERROR' for specific error events. This is useful for persistent logging and real-time error monitoring. Dependencies include the AutoX.js environment. ```javascript // Log to file console.setGlobalLogConfig({ file: "/sdcard/autoxjs_log.txt" }); // Listen to console events console.emitter.on("println", (log, level, levelString) => { // Process all console output // Don't print here or infinite loop! }); console.emitter.on("ERROR", (log, level, levelString) => { // Only capture ERROR level logs // Can send to remote server, etc. }); ``` -------------------------------- ### Work with File Streams - JavaScript Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt This section illustrates how to use file streams for efficient reading and writing of large files. `open()` creates a stream, `readline()` reads line by line, and `write()` and `writeline()` write data. Streams require explicit closing. ```javascript // Work with file streams for large files var file = open("/sdcard/largefile.txt", "r"); var line = file.readline(); while (line != null) { log(line); line = file.readline(); } file.close(); // Write to file with stream var output = open("/sdcard/output.txt", "w"); output.write("Line 1\n"); output.write("Line 2\n"); output.writeline("Line 3"); output.close(); ``` -------------------------------- ### JavaScript VSCode Plugin WebSocket Client Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt Establishes a WebSocket connection specifically for a VSCode plugin, allowing communication between the plugin and a server. It handles connection events, receives commands like 'run_script' and 'save_file', and sends confirmations. Dependencies include OkHttp3 and VSCode's built-in modules. ```javascript var vscodeClient = new OkHttpClient.Builder() .retryOnConnectionFailure(true) .build(); var vscodeRequest = new Request.Builder() .url("ws://192.168.1.100:9317") .build(); vscodeListener = { onOpen: function(ws, response) { console.log("Connected to VSCode"); // Send device info ws.send(JSON.stringify({ type: "hello", data: { device_name: device.model, client_version: app.versionCode, app_version: app.versionName, app_version_code: app.versionCode } })); }, onMessage: function(ws, msg) { var data = JSON.parse(msg); // Handle different message types from VSCode if (data.type === "command") { switch(data.command) { case "run_script": // Execute script code eval(data.script); break; case "save_file": files.write(data.path, data.content); ws.send(JSON.stringify({type: "saved", path: data.path})); break; } } }, onFailure: function(ws, t, response) { console.error("VSCode connection failed: " + t); } }; var vscodeWs = vscodeClient.newWebSocket( vscodeRequest, new WebSocketListener(vscodeListener) ); ``` -------------------------------- ### Load Image from URL and Copy - JavaScript Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt Shows how to load an image directly from a web URL and create a copy of an existing image. Both operations require the loaded/copied image objects to be recycled when no longer needed. ```javascript // Load image from URL var webImg = images.load("https://example.com/image.jpg"); if (webImg) { log("Downloaded image"); webImg.recycle(); } // Copy image var original = images.read("/sdcard/original.png"); var copy = images.copy(original); // Modify copy without affecting original original.recycle(); copy.recycle(); ``` -------------------------------- ### Write and Append to Files - JavaScript Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt Demonstrates writing text content to a file, which overwrites existing content, and appending text to the end of a file. It also shows how to write raw byte data to a file, useful for binary formats. ```javascript // Write text to file (overwrites) files.write("/sdcard/output.txt", "This is the file content"); app.viewFile("/sdcard/output.txt"); // Write binary data var bytes = [0x48, 0x65, 0x6C, 0x6C, 0x6F]; // "Hello" files.writeBytes("/sdcard/binary.dat", bytes); // Append text to file files.append("/sdcard/log.txt", "New log entry\n"); files.append("/sdcard/log.txt", "Another entry\n"); ``` -------------------------------- ### Delete Files and Directories - JavaScript Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt Provides methods to remove files and empty directories using `files.remove()`, and to recursively delete a directory and all its contents using `files.removeDir()`. Use with caution. ```javascript // Delete file or empty directory files.remove("/sdcard/tempfile.txt"); // Delete directory and all contents files.removeDir("/sdcard/TempFolder/"); ``` -------------------------------- ### JavaScript UI Element Interaction and Automation Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt This snippet demonstrates various methods for interacting with UI elements in an application using JavaScript. It covers enabling accessibility services, clicking, long-pressing, inputting and setting text, scrolling, finding elements by different selectors (text, description, ID, class, package name), combining selectors, using text patterns, waiting for elements, checking existence, finding multiple elements, accessing element properties, navigating the UI hierarchy, and performing input operations on EditText fields. ```javascript auto.waitFor(); // Click button by text click("Send"); click("Settings"); // Click specific occurrence of text (second button with "OK") click("OK", 1); // Click until successful while (!click("Next")); // Long press on text longClick("Delete"); // Input text in input fields input("Hello World"); // Inputs in all input fields input(0, "Username"); // Inputs in first input field input(1, "Password"); // Inputs in second input field // Set text (replaces existing content) setText("New text content"); setText(0, "Replace first input"); // Scroll operations scrollUp(); // Scroll up/left on largest scrollable scrollDown(); // Scroll down/right scrollUp(0); // Scroll first scrollable element scrollDown(1); // Scroll second scrollable element // Find and click elements by various selectors // Find by text var sendButton = text("Send").findOne(); sendButton.click(); // Find by description desc("Search").findOne().click(); // Find by id id("action_search").findOne().click(); id("com.tencent.mm:id/send_btn").findOne().click(); // Find by className className("Button").findOne().click(); className("EditText").findOne().setText("Input text"); // Combine multiple conditions var button = className("ImageView") .desc("Send") .clickable(true) .findOne(); button.click(); // Complex selector with multiple criteria var widget = text("Settings") .className("TextView") .packageName("com.android.settings") .clickable() .findOne(); // Find with text patterns textContains("Search").findOne().click(); // Contains "Search" textStartsWith("Hello").findOne().click(); // Starts with "Hello" textEndsWith("...").findOne().click(); // Ends with "..." textMatches(/\d+/).findOne(); // Regex matching // Wait for element to appear textContains("Loading").waitFor(); log("Element appeared!"); // Check if element exists if (text("Logout").exists()) { log("Logout button found"); text("Logout").findOne().click(); } // Find all matching elements var allButtons = className("Button").find(); allButtons.forEach(function(btn) { log("Button text: " + btn.text()); }); // Work with element properties var element = id("username").findOne(); log("Text: " + element.text()); log("ID: " + element.id()); log("Clickable: " + element.clickable()); log("Bounds: " + element.bounds()); // Get element position and click coordinates var searchIcon = desc("Search").findOne(); var bounds = searchIcon.bounds(); click(bounds.centerX(), bounds.centerY()); // Navigate element hierarchy var listView = className("ListView").findOne(); var childCount = listView.childCount(); for (var i = 0; i < childCount; i++) { var child = listView.child(i); log("Child " + i + ": " + child.text()); } // Get parent element var button = text("OK").findOne(); var parent = button.parent(); log("Parent class: " + parent.className()); // Input operations on EditText var editText = className("EditText").findOne(); editText.setText("New content"); editText.setSelection(0, 3); // Select first 3 characters editText.copy(); // Copy selection editText.paste(); // Paste clipboard // Scroll operations on scrollable views var scrollView = className("ScrollView").scrollable().findOne(); scrollView.scrollForward(); // Scroll down/right scrollView.scrollBackward(); // Scroll up/left scrollView.scrollUp(); scrollView.scrollDown(); // Find elements within a parent var list = id("message_list").findOne(); list.children().forEach(function(item) { var sender = item.findOne(id("sender_name")); var message = item.findOne(id("message_text")); if (sender && message) { log(sender.text() + ": " + message.text()); } }); // Wait for element with timeout var element = text("Done").findOne(5000); // Wait max 5 seconds if (element != null) { element.click(); } else { toast("Element not found within timeout"); } ``` -------------------------------- ### Scale and Rotate Images - JavaScript Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt Demonstrates scaling images by a factor (uniformly or non-uniformly) and rotating them by a specified angle. New image objects are created and require recycling. ```javascript // Scale image by factor var img = images.read("/sdcard/photo.png"); // Scale to 50% of original size var scaled = images.scale(img, 0.5, 0.5); images.save(scaled, "/sdcard/scaled.png"); // Scale with different X and Y factors var stretched = images.scale(img, 2.0, 0.5); images.save(stretched, "/sdcard/stretched.png"); img.recycle(); scaled.recycle(); stretched.recycle(); // Rotate image var img = images.read("/sdcard/portrait.png"); // Rotate 90 degrees counter-clockwise var rotated90 = images.rotate(img, 90); images.save(rotated90, "/sdcard/landscape.png"); // Rotate 45 degrees around center var rotated45 = images.rotate(img, 45); images.save(rotated45, "/sdcard/rotated45.png"); img.recycle(); rotated90.recycle(); rotated45.recycle(); ``` -------------------------------- ### Copy, Move, and Rename Files - JavaScript Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt These functions provide utilities for managing files by copying them to a new location, moving them (which includes renaming), and specifically renaming files. `files.renameWithoutExtension` is useful for changing the base name. ```javascript // Copy file var success = files.copy("/sdcard/source.txt", "/sdcard/backup/source.txt"); log("Copy success: " + success); // Move file files.move("/sdcard/oldlocation.txt", "/sdcard/newlocation.txt"); // Rename file files.rename("/sdcard/oldname.txt", "newname.txt"); files.renameWithoutExtension("/sdcard/doc.txt", "document"); // Becomes "document.txt" ``` -------------------------------- ### Read and Save Images - JavaScript Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt Demonstrates reading images from local files and saving them in various formats (PNG, JPEG, WebP) with specified quality. It handles potential read failures and requires image recycling after use. ```javascript var img = images.read("/sdcard/photo.png"); if (img == null) { toast("Failed to load image"); } else { log("Image loaded: " + img.getWidth() + "x" + img.getHeight()); // Remember to recycle when done img.recycle(); } // Save image with different formats and quality var img = images.read("/sdcard/photo.png"); // Save as PNG (lossless) images.save(img, "/sdcard/output.png", "png", 100); // Save as JPEG with 50% quality (smaller file) images.save(img, "/sdcard/output.jpg", "jpeg", 50); // Save as WebP images.save(img, "/sdcard/output.webp", "webp", 80); img.recycle(); ``` -------------------------------- ### Take Screenshots - JavaScript Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt Provides methods for capturing screenshots of the device screen. `takeScreenshot()` is a blocking call, while `takeScreenshotAsync()` performs the capture asynchronously. Screenshots from `takeScreenshot()` require recycling, but those from `captureScreen()` do not. ```javascript // Take screenshot using accessibility service var screenshot = auto.takeScreenshot(); if (screenshot) { images.save(screenshot, "/sdcard/screenshot.png"); toast("Screenshot saved"); // Note: captureScreen() screenshots don't need recycling } // Async screenshot (non-blocking) auto.takeScreenshotAsync(function(image, errCode) { if (errCode) { toast("Screenshot failed: " + errCode); } else { images.save(image, "/sdcard/async_screenshot.png"); toast("Async screenshot saved"); } }); ``` -------------------------------- ### Read Text and Binary Files - JavaScript Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt This section covers reading file content as text, with support for specific character encodings like UTF-8, and reading files as raw bytes for binary data such as images. It's essential for data retrieval. ```javascript // Read text file var content = files.read("/sdcard/config.txt"); log(content); // Read text file with specific encoding var utf8Content = files.read("/sdcard/data.txt", "utf-8"); // Read binary file as bytes var imageBytes = files.readBytes("/sdcard/photo.png"); log("File size: " + imageBytes.length + " bytes"); ``` -------------------------------- ### JavaScript WebSocket Client with OkHttp3 Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt Implements a WebSocket client using OkHttp3 in JavaScript for real-time messaging. It handles connection, message sending/receiving, error handling, and reconnection. Dependencies include the OkHttp3 library. It sends and receives JSON messages. ```javascript importPackage(Packages["okhttp3"]); // Create HTTP client with reconnection support var client = new OkHttpClient.Builder() .retryOnConnectionFailure(true) .build(); // Create WebSocket request var request = new Request.Builder() .url("ws://192.168.1.100:9317") // WebSocket server URL .build(); // Clear any existing connections client.dispatcher().cancelAll(); // Define WebSocket event listener myListener = { onOpen: function(webSocket, response) { print("WebSocket connected"); // Send initial handshake message var handshake = { type: "hello", data: { device_name: "Android Device", client_version: 123, app_version: 456, app_version_code: "1.0.0" } }; webSocket.send(JSON.stringify(handshake)); }, onMessage: function(webSocket, msg) { // msg can be string or byte array depending on server print("Received message:"); print(msg); // Parse JSON message try { var data = JSON.parse(msg); if (data.type === "command") { print("Executing command: " + data.command); // Handle command } } catch(e) { print("Non-JSON message: " + msg); } }, onClosing: function(webSocket, code, response) { print("WebSocket closing... Code: " + code); }, onClosed: function(webSocket, code, response) { print("WebSocket closed. Code: " + code); }, onFailure: function(webSocket, t, response) { print("WebSocket error:"); print(t); // Attempt reconnection after delay setTimeout(function() { print("Attempting reconnection..."); // Recreate WebSocket connection }, 5000); } }; // Create WebSocket connection var webSocket = client.newWebSocket( request, new WebSocketListener(myListener) ); // Send messages to server setTimeout(function() { var message = { type: "status", data: { battery: device.getBattery(), screen: device.isScreenOn() } }; webSocket.send(JSON.stringify(message)); }, 3000); // Periodic heartbeat setInterval(function() { if (webSocket) { webSocket.send(JSON.stringify({type: "ping"})); } }, 30000); // Every 30 seconds // Keep main thread alive setInterval(function() { // Prevent script from exiting }, 1000); // Close connection gracefully (call when needed) function closeWebSocket() { if (webSocket) { webSocket.close(1000, "Normal closure"); } } ``` -------------------------------- ### Check File/Directory Status and Existence - JavaScript Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt These functions allow you to check if a given path points to a file or directory, determine if a directory is empty, and verify if a file or directory exists. They are fundamental for conditional file operations. ```javascript // Check if path is file or directory log(files.isFile("/sdcard/document.txt")); // true log(files.isDir("/sdcard/Documents/")); // true log(files.isEmptyDir("/sdcard/EmptyFolder/")); // true or false // Check file existence if (files.exists("/sdcard/myfile.txt")) { log("File exists"); } ``` -------------------------------- ### Path Manipulation - JavaScript Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt This function helps in constructing correct file paths by joining multiple path components. It handles platform-specific separators, ensuring cross-platform compatibility for file access. ```javascript // Join paths var fullPath = files.join("/sdcard/", "subfolder", "file.txt"); log(fullPath); // "/sdcard/subfolder/file.txt" ``` -------------------------------- ### Crop and Resize Images - JavaScript Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt Covers cropping an image to a specific rectangular region and resizing it to exact dimensions. Both operations return new image objects that must be recycled. ```javascript // Crop image region var src = images.read("/sdcard/screenshot.png"); // Crop 400x400 region starting at (100, 100) var cropped = images.clip(src, 100, 100, 400, 400); images.save(cropped, "/sdcard/cropped.png"); src.recycle(); cropped.recycle(); // Resize image to specific dimensions var img = images.read("/sdcard/large.png"); // Resize to 800x600 var resized = images.resize(img, [800, 600]); images.save(resized, "/sdcard/resized.png"); img.recycle(); resized.recycle(); ``` -------------------------------- ### Base64 and Byte Array Conversion - JavaScript Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt Explains how to convert images to and from Base64 strings, as well as byte arrays. This is useful for storing or transmitting image data. Remember to recycle image objects after conversion and decoding. ```javascript // Base64 encoding/decoding var img = images.read("/sdcard/icon.png"); var base64Data = images.toBase64(img, "png", 100); log("Base64 length: " + base64Data.length); img.recycle(); // Decode from Base64 var decodedImg = images.fromBase64(base64Data); images.save(decodedImg, "/sdcard/decoded.png"); decodedImg.recycle(); // Byte array operations var img = images.read("/sdcard/data.png"); var bytes = images.toBytes(img, "png", 100); log("Image bytes: " + bytes.length); var imgFromBytes = images.fromBytes(bytes); imgFromBytes.recycle(); img.recycle(); ``` -------------------------------- ### List Directory Contents - JavaScript Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt Allows you to retrieve a list of all files and subdirectories within a specified directory. It also supports filtering the results using a callback function, enabling selective retrieval based on criteria like file extension. ```javascript // List directory contents var fileList = files.listDir("/sdcard/"); log(fileList); // List with filter (only .js files) var dir = "/sdcard/scripts/"; var jsFiles = files.listDir(dir, function(name) { return name.endsWith(".js") && files.isFile(files.join(dir, name)); }); log(jsFiles); ``` -------------------------------- ### Concatenate and Grayscale Images - JavaScript Source: https://context7.com/nakanosanku/autoxv6doc/llms.txt Shows how to join images horizontally or vertically and convert color images to grayscale. The resulting images are new objects and need to be recycled. ```javascript // Concatenate images var img1 = images.read("/sdcard/left.png"); var img2 = images.read("/sdcard/right.png"); // Join horizontally (img2 to right of img1) var horizontal = images.concat(img1, img2, "RIGHT"); images.save(horizontal, "/sdcard/horizontal.png"); // Join vertically (img2 below img1) var vertical = images.concat(img1, img2, "BOTTOM"); images.save(vertical, "/sdcard/vertical.png"); img1.recycle(); img2.recycle(); horizontal.recycle(); vertical.recycle(); // Grayscale conversion var colorImg = images.read("/sdcard/color.png"); var grayImg = images.grayscale(colorImg); images.save(grayImg, "/sdcard/grayscale.png"); colorImg.recycle(); grayImg.recycle(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.