### Install, Uninstall, and Manage Android Apps with AdvancedSharpAdbClient Source: https://context7.com/sharpadb/advancedsharpadbclient/llms.txt Handles APK installation, uninstallation, and package queries using PackageManager and AdbClient.Install. Supports single APKs, split APKs (App Bundles), and streaming installs. Includes options for reinstalling, downgrading, and keeping app data during uninstallation. Progress callbacks are provided for installation and upload operations. ```csharp using AdvancedSharpAdbClient; using AdvancedSharpAdbClient.DeviceCommands; AdbClient adbClient = new AdbClient(); DeviceData device = adbClient.GetDevices().First(); // Method 1: Install using PackageManager (copies APK to device first) PackageManager manager = new PackageManager(adbClient, device); // Install a single APK with progress callback manager.InstallPackage(@"C:\\Apps\\myapp.apk", progress => { Console.WriteLine($"State: {progress.State}, Progress: {progress.PackageFinished}/{progress.PackageRequired}"); }, "-r", "-d"); // -r: reinstall, -d: allow downgrade // Install split APKs (Android App Bundle) manager.InstallMultiplePackage( @"C:\\Apps\\base.apk", new[] { @"C:\\Apps\\split_config.arm64_v8a.apk", @"C:\\Apps\\split_config.en.apk" }, progress => Console.WriteLine($"Progress: {progress.UploadProgress:F1}%") ); // Method 2: Install using streaming (faster, no temp file on device) using (FileStream apkStream = File.OpenRead(@"C:\\Apps\\myapp.apk")) { adbClient.Install(device, apkStream, progress => { if (progress.State == PackageInstallProgressState.Uploading) Console.WriteLine($"Uploading: {progress.UploadProgress:F1}%"); else Console.WriteLine($"State: {progress.State}"); }, "-r"); } // Uninstall an app manager.UninstallPackage("com.example.myapp"); // Or keep data: manager.UninstallPackage("com.example.myapp", "-k"); // List installed packages manager.RefreshPackages(); foreach (var package in manager.Packages) { Console.WriteLine($"Package: {package.Key}, Path: {package.Value}"); } // Get version info VersionInfo versionInfo = manager.GetVersionInfo("com.android.chrome"); Console.WriteLine($"Version: {versionInfo.VersionName} ({versionInfo.VersionCode})"); ``` -------------------------------- ### Start Adb Server using AdvancedSharpAdbClient Source: https://github.com/sharpadb/advancedsharpadbclient/blob/main/README.md Demonstrates how to start the adb server programmatically using the AdbServer.StartServer method. It checks if the server is already running and attempts to start it if not, providing feedback on the success of the operation. Requires the path to adb.exe. ```csharp if (!AdbServer.Instance.GetStatus().IsRunning) { AdbServer server = new AdbServer(); StartServerResult result = server.StartServer(@"C:\\adb\\adb.exe", false); if (result != StartServerResult.Started) { Console.WriteLine("Can't start adb server"); } } ``` -------------------------------- ### Manage ADB Server Lifecycle with AdbServer Source: https://context7.com/sharpadb/advancedsharpadbclient/llms.txt Demonstrates how to check the status of the ADB server and start it using a specified path to the adb.exe binary. It handles different startup results to ensure the server is ready for communication. ```csharp using AdvancedSharpAdbClient; // Check if ADB server is running and start it if needed if (!AdbServer.Instance.GetStatus().IsRunning) { AdbServer server = new AdbServer(); StartServerResult result = server.StartServer(@"C:\Android\platform-tools\adb.exe", restartServerIfNewer: false); switch (result) { case StartServerResult.Started: Console.WriteLine("ADB server started successfully"); break; case StartServerResult.AlreadyRunning: Console.WriteLine("ADB server was already running"); break; case StartServerResult.RestartedOutdatedDaemon: Console.WriteLine("Restarted outdated ADB daemon"); break; } } // Get server status AdbServerStatus status = AdbServer.Instance.GetStatus(); Console.WriteLine($"Running: {status.IsRunning}, Version: {status.Version}"); ``` -------------------------------- ### Execute Asynchronous ADB Operations Source: https://context7.com/sharpadb/advancedsharpadbclient/llms.txt Demonstrates non-blocking execution of shell commands, app installation, file transfers, and UI automation using async/await patterns. ```csharp using AdvancedSharpAdbClient; using AdvancedSharpAdbClient.DeviceCommands; AdbClient adbClient = new AdbClient(); DeviceData device = (await adbClient.GetDevicesAsync()).First(); // Async shell command ConsoleOutputReceiver receiver = new ConsoleOutputReceiver(); await adbClient.ExecuteRemoteCommandAsync("pm list packages", device, receiver, Encoding.UTF8); // Async app installation using (FileStream apk = File.OpenRead(@"C:\app.apk")) { await adbClient.InstallAsync(device, apk, progress => { Console.WriteLine($"Progress: {progress.UploadProgress}%"); }); } // Async screenshot Framebuffer screenshot = await adbClient.GetFrameBufferAsync(device, CancellationToken.None); // Async file transfer using (SyncService service = new SyncService(adbClient, device)) { using (FileStream stream = File.Create(@"C:\file.txt")) { await service.PullAsync("/sdcard/file.txt", stream); } } // Async device client operations DeviceClient deviceClient = new DeviceClient(adbClient, device); Element? element = await deviceClient.FindElementAsync("//node[@text='OK']", TimeSpan.FromSeconds(5)); if (element != null) { await element.ClickAsync(); } ``` -------------------------------- ### Install and Uninstall Applications Source: https://github.com/sharpadb/advancedsharpadbclient/blob/main/README.md Manage application installations and uninstalls on the Android device. This can be done using the PackageManager or directly via the AdbClient. Installation requires the path to the APK file, while uninstallation requires the package name. ```cs static void Main(string[] args) { ... PackageManager manager = new PackageManager(adbClient, deviceData); manager.InstallPackage(@"C:\Users\me\Documents\mypackage.apk"); manager.UninstallPackage("com.android.app"); ... } ``` ```cs static void Main(string[] args) { ... using (FileStream stream = File.OpenRead("Application.apk")) { adbClient.Install(device, stream); adbClient.Uninstall(device, "com.android.app"); } ... } ``` -------------------------------- ### Install Multiple Applications (Split APKs) Source: https://github.com/sharpadb/advancedsharpadbclient/blob/main/README.md Install applications that consist of multiple APK files (split APKs). This functionality allows installing a base APK along with its split components, or adding split APKs to an existing base application identified by its package name. ```cs static void Main(string[] args) { ... PackageManager manager = new PackageManager(adbClient, deviceData); manager.InstallMultiplePackage(@"C:\Users\me\Documents\base.apk", new[] { @"C:\Users\me\Documents\split_1.apk", @"C:\Users\me\Documents\split_2.apk" }); // Install split app whith base app manager.InstallMultiplePackage(new[] { @"C:\Users\me\Documents\split_3.apk", @"C:\Users\me\Documents\split_4.apk" }, "com.android.app"); // Add split app to base app which packagename is 'com.android.app' ... } ``` ```cs static void Main(string[] args) { ... adbClient.InstallMultiple(device, File.OpenRead("base.apk"), new[] { File.OpenRead("split_1.apk"), File.OpenRead("split_2.apk") }); // Install split app whith base app adbClient.InstallMultiple(device, new[] { File.OpenRead("split_3.apk"), File.OpenRead("split_4.apk") }, "com.android.app"); // Add split app to base app which packagename is 'com.android.app' ... } ``` -------------------------------- ### Install AdvancedSharpAdbClient NuGet Package Source: https://github.com/sharpadb/advancedsharpadbclient/blob/main/README.md Installs the AdvancedSharpAdbClient NuGet package using the Package Manager Console in Visual Studio. This is the primary method for adding the library to your .NET project. ```powershell PM> Install-Package AdvancedSharpAdbClient ``` -------------------------------- ### File Transfer Operations with SyncService in C# Source: https://context7.com/sharpadb/advancedsharpadbclient/llms.txt Demonstrates how to perform file transfer operations like downloading (pull), uploading (push), listing directory contents, and getting file statistics using the SyncService class. Requires the AdvancedSharpAdbClient library and a connected Android device. ```csharp using AdvancedSharpAdbClient; AdbClient adbClient = new AdbClient(); DeviceData device = adbClient.GetDevices().First(); // Download a file from device using (SyncService service = new SyncService(adbClient, device)) { using (FileStream localFile = File.Create(@"C:\\Downloads\\config.xml")) { service.Pull("/sdcard/Android/data/com.app/config.xml", localFile, progress => Console.WriteLine($"Download: {progress.ProgressPercentage:F1}%")); } } // Upload a file to device using (SyncService service = new SyncService(adbClient, device)) { using (FileStream localFile = File.OpenRead(@"C:\\Files\\data.json")) { service.Push( localFile, "/sdcard/Download/data.json", UnixFileStatus.DefaultFileMode, // 644 permission DateTimeOffset.Now, progress => Console.WriteLine($"Upload: {progress.ProgressPercentage:F1}%") ); } } // List directory contents using (SyncService service = new SyncService(adbClient, device)) { IEnumerable files = service.GetDirectoryListing("/sdcard/Download/"); foreach (FileStatistics file in files) { Console.WriteLine($"{file.Path} - Size: {file.Size} bytes, Modified: {file.Time}"); } } // Get file info using (SyncService service = new SyncService(adbClient, device)) { FileStatistics stat = service.Stat("/sdcard/Download/myfile.txt"); Console.WriteLine($"Size: {stat.Size}, Mode: {stat.FileMode}, Time: {stat.Time}"); } ``` -------------------------------- ### Start and Stop Applications Source: https://github.com/sharpadb/advancedsharpadbclient/blob/main/README.md Control the lifecycle of applications on the Android device. You can start an application by its package name or force-stop it to terminate its process. ```cs static void Main(string[] args) { ... deviceClient.StartApp("com.android.app"); deviceClient.StopApp("com.android.app"); // force-stop ... } ``` -------------------------------- ### Get Screen Hierarchy using C# Source: https://github.com/sharpadb/advancedsharpadbclient/blob/main/README.md Demonstrates how to retrieve the XML hierarchy of the current screen on an Android device using the DumpScreen method. This requires an initialized DeviceData object and an AdbClient instance. ```cs static void Main(string[] args) { ... XmlDocument screen = deviceClient.DumpScreen(); ... } ``` -------------------------------- ### Get Device Screenshot Source: https://github.com/sharpadb/advancedsharpadbclient/blob/main/README.md Capture a screenshot of the current device screen. This operation can be performed synchronously or asynchronously. The screenshot is returned as an Image object. ```cs static async void Main(string[] args) { ... Image img = adbClient.GetFrameBuffer(deviceData, CancellationToken.None); // synchronously ... Image img = await adbClient.GetFrameBufferAsync(deviceData, CancellationToken.None); // asynchronously ... } ``` -------------------------------- ### Get Attributes of a UI Element Source: https://github.com/sharpadb/advancedsharpadbclient/blob/main/README.md Retrieves all attributes of a specified UI element found on the Android device screen. Attributes like 'text' and 'bounds' can be accessed directly from the element's Attributes dictionary. ```csharp static void Main(string[] args) { ... Element element = deviceClient.FindElement("//node[@resource-id='Login']", TimeSpan.FromSeconds(3)); string eltext = element.Attributes["text"]; string bounds = element.Attributes["bounds"]; ... } ``` -------------------------------- ### Clear Input Text Fields Source: https://github.com/sharpadb/advancedsharpadbclient/blob/main/README.md Clear text from an input field. The recommended method involves specifying the maximum number of characters to erase. An alternative, potentially unstable method, clears text by getting the element's text attribute and removing characters. ```cs static void Main(string[] args) { ... deviceClient.ClearInput(25); // The argument is to specify the maximum number of characters to be erased ... } ``` ```cs static void Main(string[] args) { ... deviceClient.FindElement("//node[@resource-id='Login']").ClearInput(); // Get element text attribute and remove text length symbols ... } ``` -------------------------------- ### Screenshot Capture in C# Source: https://context7.com/sharpadb/advancedsharpadbclient/llms.txt Shows how to capture the device screen framebuffer as an image. Includes synchronous and asynchronous capture methods, accessing raw pixel data, and creating a reusable framebuffer for multiple captures. Requires the AdvancedSharpAdbClient library. ```csharp using AdvancedSharpAdbClient; using System.Threading; AdbClient adbClient = new AdbClient(); DeviceData device = adbClient.GetDevices().First(); // Capture screenshot synchronously Framebuffer framebuffer = adbClient.GetFrameBuffer(device); Console.WriteLine($"Screenshot: {framebuffer.Header.Width}x{framebuffer.Header.Height}"); Console.WriteLine($"Color format: {framebuffer.Header.ColorSpace}"); // Access raw pixel data byte[] pixels = framebuffer.Data; // Convert to Image using System.Drawing or other library // Image image = framebuffer.ToImage(); // Capture screenshot asynchronously Framebuffer asyncBuffer = await adbClient.GetFrameBufferAsync(device, CancellationToken.None); // Create reusable framebuffer for multiple captures Framebuffer reusableBuffer = adbClient.CreateFramebuffer(device); reusableBuffer.Refresh(); // Capture // ... process image ... reusableBuffer.Refresh(); // Capture again ``` -------------------------------- ### Connect and Interact with Android Devices Source: https://context7.com/sharpadb/advancedsharpadbclient/llms.txt Shows how to use AdbClient to list connected devices, establish TCP/IP connections, pair devices for wireless debugging, and execute remote shell commands. ```csharp using AdvancedSharpAdbClient; // Create ADB client instance AdbClient adbClient = new AdbClient(); // Get all connected devices IEnumerable devices = adbClient.GetDevices(); foreach (DeviceData device in devices) { Console.WriteLine($"Serial: {device.Serial}"); Console.WriteLine($"State: {device.State}"); } // Connect to a device over TCP/IP string result = adbClient.Connect("192.168.1.100", 5555); // Execute a shell command ConsoleOutputReceiver receiver = new ConsoleOutputReceiver(); DeviceData device = adbClient.GetDevices().FirstOrDefault(); if (device != null) { adbClient.ExecuteRemoteCommand("getprop ro.product.model", device, receiver, Encoding.UTF8); Console.WriteLine($"Device Model: {receiver}"); } ``` -------------------------------- ### Shell Command Execution in C# Source: https://context7.com/sharpadb/advancedsharpadbclient/llms.txt Illustrates how to execute arbitrary shell commands on Android devices and capture their output using either a ConsoleOutputReceiver for complete output or an enumerable stream for real-time processing. Supports commands requiring root privileges after calling adbClient.Root(). Requires the AdvancedSharpAdbClient library. ```csharp using AdvancedSharpAdbClient; using System.Text; using System.Threading; AdbClient adbClient = new AdbClient(); DeviceData device = adbClient.GetDevices().First(); // Execute command with ConsoleOutputReceiver ConsoleOutputReceiver receiver = new ConsoleOutputReceiver(); adbClient.ExecuteRemoteCommand("ls -la /sdcard/", device, receiver, Encoding.UTF8); Console.WriteLine(receiver.ToString()); // Execute command with enumerable output (streaming) foreach (string line in adbClient.ExecuteRemoteEnumerable("logcat -d", device, Encoding.UTF8)) { Console.WriteLine(line); if (line.Contains("ERROR")) break; // Stop early if needed } // Get device properties ConsoleOutputReceiver propReceiver = new ConsoleOutputReceiver(); adbClient.ExecuteRemoteCommand("getprop", device, propReceiver, Encoding.UTF8); // Execute commands that require root try { adbClient.Root(device); // Restart adbd with root privileges Thread.Sleep(3000); // Wait for restart // Now execute root commands ConsoleOutputReceiver rootReceiver = new ConsoleOutputReceiver(); adbClient.ExecuteRemoteCommand("cat /data/system/packages.xml", device, rootReceiver, Encoding.UTF8); adbClient.Unroot(device); // Return to normal mode } catch (AdbException ex) { Console.WriteLine($"Root failed: {ex.Message}"); } ``` -------------------------------- ### UI Automation with DeviceClient in AdvancedSharpAdbClient Source: https://context7.com/sharpadb/advancedsharpadbclient/llms.txt Provides UI automation capabilities including finding elements by XPath, clicking, swiping, and sending text input. It allows fetching the screen's XML hierarchy, locating elements with timeouts, and performing various gestures and input actions. Also supports checking app status and starting/stopping applications. ```csharp using AdvancedSharpAdbClient; using AdvancedSharpAdbClient.DeviceCommands; AdbClient adbClient = new AdbClient(); DeviceData device = adbClient.GetDevices().First(); DeviceClient deviceClient = new DeviceClient(adbClient, device); // Get current screen XML hierarchy XmlDocument screen = deviceClient.DumpScreen(); Console.WriteLine(screen?.OuterXml); // Find element by XPath with timeout Element? loginButton = deviceClient.FindElement( "//node[@text='Login']", TimeSpan.FromSeconds(5) ); if (loginButton != null) { Console.WriteLine($"Found: {loginButton.Text} at {loginButton.Bounds}"); Console.WriteLine($"Class: {loginButton.Class}"); Console.WriteLine($"ResourceID: {loginButton.ResourceID}"); // Click the element loginButton.Click(); } // Find multiple elements IEnumerable buttons = deviceClient.FindElements( "//node[@class='android.widget.Button']", TimeSpan.FromSeconds(3) ); foreach (Element button in buttons) { Console.WriteLine($"Button: {button.Text}"); } // Click by coordinates deviceClient.Click(500, 1200); // Swipe gesture (from point1 to point2 in 300ms) deviceClient.Swipe(500, 1500, 500, 500, 300); // Find text field and enter text Element? usernameField = deviceClient.FindElement("//node[@resource-id='com.app:id/username']"); if (usernameField != null) { usernameField.Click(); usernameField.SendText("myusername"); } // Send text (requires focused input field) deviceClient.SendText("Hello World"); // Clear input field (delete 20 characters) deviceClient.ClearInput(20); // Send key events deviceClient.SendKeyEvent("KEYCODE_ENTER"); deviceClient.SendKeyEvent("KEYCODE_TAB"); deviceClient.ClickBackButton(); // KEYCODE_BACK deviceClient.ClickHomeButton(); // KEYCODE_HOME // Check app status AppStatus status = deviceClient.GetAppStatus("com.example.myapp"); Console.WriteLine($"App status: {status}"); // Foreground, Background, or Stopped // Start/Stop apps deviceClient.StartApp("com.example.myapp"); deviceClient.StopApp("com.example.myapp"); // force-stop ``` -------------------------------- ### Manage Port Forwarding with AdvancedSharpAdbClient Source: https://context7.com/sharpadb/advancedsharpadbclient/llms.txt Demonstrates how to establish, list, and remove port forwards between local ports and Android device ports or Unix sockets. Supports both standard forwarding and reverse forwarding configurations. ```csharp using AdvancedSharpAdbClient; AdbClient adbClient = new AdbClient(); DeviceData device = adbClient.GetDevices().First(); // Forward local port to device port int boundPort = adbClient.CreateForward(device, "tcp:8080", "tcp:8080", allowRebind: true); Console.WriteLine($"Forwarding established on port {boundPort}"); // Forward to a Unix socket on device adbClient.CreateForward(device, "tcp:5000", "localabstract:my_socket", allowRebind: true); // List all forwards for a device IEnumerable forwards = adbClient.ListForward(device); foreach (ForwardData forward in forwards) { Console.WriteLine($"{forward.Local} -> {forward.Remote}"); } // Remove specific forward adbClient.RemoveForward(device, 8080); // Remove all forwards adbClient.RemoveAllForwards(device); // Reverse forwarding (device connects to PC) adbClient.CreateReverseForward(device, "tcp:9000", "tcp:9000", allowRebind: true); // List reverse forwards IEnumerable reverseForwards = adbClient.ListReverseForward(device); // Remove reverse forwards adbClient.RemoveReverseForward(device, "tcp:9000"); adbClient.RemoveAllReverseForwards(device); ``` -------------------------------- ### Reboot Android Devices Source: https://context7.com/sharpadb/advancedsharpadbclient/llms.txt Shows how to trigger device reboots into various states including standard reboot, bootloader, recovery, and sideload modes. ```csharp using AdvancedSharpAdbClient; AdbClient adbClient = new AdbClient(); DeviceData device = adbClient.GetDevices().First(); // Regular reboot adbClient.Reboot("", device); // Reboot to bootloader (fastboot mode) adbClient.Reboot("bootloader", device); // Reboot to recovery mode adbClient.Reboot("recovery", device); // Reboot to sideload mode (for OTA updates) adbClient.Reboot("sideload", device); ``` -------------------------------- ### Shell Command Execution Source: https://context7.com/sharpadb/advancedsharpadbclient/llms.txt Execute arbitrary shell commands on Android devices and capture output using receivers or enumerable streams. ```APIDOC ## Shell Command Execution API ### Description Allows execution of shell commands on connected Android devices and retrieval of their output. ### Methods #### Execute Remote Command (with Receiver) Executes a command and captures its output using a specified receiver. - **Endpoint**: Not applicable (uses AdbClient instance) - **Method**: `adbClient.ExecuteRemoteCommand(string command, DeviceData device, IShellOutputReceiver receiver, Encoding encoding)` - **Parameters**: - `command` (string) - Required - The shell command to execute. - `device` (DeviceData) - Required - The target device. - `receiver` (IShellOutputReceiver) - Required - An object to process the command output. - `encoding` (Encoding) - Required - The character encoding for the output. #### Execute Remote Enumerable Command Executes a command and returns its output as an enumerable stream of strings. - **Endpoint**: Not applicable (uses AdbClient instance) - **Method**: `adbClient.ExecuteRemoteEnumerable(string command, DeviceData device, Encoding encoding)` - **Parameters**: - `command` (string) - Required - The shell command to execute. - `device` (DeviceData) - Required - The target device. - `encoding` (Encoding) - Required - The character encoding for the output. - **Returns**: `IEnumerable` - An enumerable collection of output lines. #### Get Device Properties Retrieves system properties of the device. - **Endpoint**: Not applicable (uses AdbClient instance) - **Method**: `adbClient.ExecuteRemoteCommand("getprop", device, propReceiver, Encoding.UTF8)` #### Root Device Restarts the adbd daemon with root privileges. - **Endpoint**: Not applicable (uses AdbClient instance) - **Method**: `adbClient.Root(DeviceData device)` - **Throws**: `AdbException` if root fails. #### Unroot Device Restarts the adbd daemon to normal user mode. - **Endpoint**: Not applicable (uses AdbClient instance) - **Method**: `adbClient.Unroot(DeviceData device)` ### Request Example (ConsoleOutputReceiver) ```csharp ConsoleOutputReceiver receiver = new ConsoleOutputReceiver(); adbClient.ExecuteRemoteCommand("ls -la /sdcard/", device, receiver, Encoding.UTF8); Console.WriteLine(receiver.ToString()); ``` ### Request Example (Enumerable Output) ```csharp foreach (string line in adbClient.ExecuteRemoteEnumerable("logcat -d", device, Encoding.UTF8)) { Console.WriteLine(line); if (line.Contains("ERROR")) break; // Stop early if needed } ``` ### Request Example (Rooting and Executing Command) ```csharp try { adbClient.Root(device); // Restart adbd with root privileges Thread.Sleep(3000); // Wait for restart ConsoleOutputReceiver rootReceiver = new ConsoleOutputReceiver(); adbClient.ExecuteRemoteCommand("cat /data/system/packages.xml", device, rootReceiver, Encoding.UTF8); adbClient.Unroot(device); // Return to normal mode } catch (AdbException ex) { Console.WriteLine($"Root failed: {ex.Message}"); } ``` ### Response Example (ConsoleOutputReceiver) ```text -rw-rw---- 1 root sdcard_rw 12345 Oct 27 10:00 file.txt drwxrwx--x 2 root sdcard_rw 4096 Oct 26 09:00 directory ``` ``` -------------------------------- ### Execute Shell Commands (Sync/Async) using C# Source: https://github.com/sharpadb/advancedsharpadbclient/blob/main/README.md Illustrates how to execute shell commands on an Android device using both synchronous and asynchronous methods. It utilizes the ExecuteRemoteCommand and ExecuteRemoteCommandAsync methods, requiring an AdbClient, DeviceData, and a receiver for output. ```cs static async void Main(string[] args) { ... ConsoleOutputReceiver receiver = new ConsoleOutputReceiver(); adbClient.ExecuteRemoteCommand("echo Hello, World", device, receiver); // synchronously ... await adbClient.ExecuteRemoteCommandAsync("echo Hello, World", device, receiver, default); // asynchronously ... } ``` -------------------------------- ### Monitor Device Connection Events Source: https://context7.com/sharpadb/advancedsharpadbclient/llms.txt Utilizes the DeviceMonitor class to subscribe to real-time events such as device connection, disconnection, and state changes. This is essential for reactive applications that need to respond to hardware changes. ```csharp using AdvancedSharpAdbClient; // Create device monitor DeviceMonitor monitor = new DeviceMonitor(); // Subscribe to device events monitor.DeviceConnected += (sender, e) => { Console.WriteLine($"Device connected: {e.Device.Serial} - {e.Device.Model}"); }; monitor.DeviceDisconnected += (sender, e) => { Console.WriteLine($"Device disconnected: {e.Device.Serial}"); }; // Start monitoring monitor.Start(); // Clean up when done monitor.Dispose(); ``` -------------------------------- ### Navigate with Back and Home Buttons Source: https://github.com/sharpadb/advancedsharpadbclient/blob/main/README.md Simulate pressing the Back and Home buttons on the Android device. These actions are useful for navigating the device's interface or returning to the home screen. ```cs static void Main(string[] args) { ... deviceClient.ClickBackButton(); // Click Back button ... deviceClient.ClickHomeButton(); // Click Home button ... } ``` -------------------------------- ### Stream Android Logcat Logs Source: https://context7.com/sharpadb/advancedsharpadbclient/llms.txt Provides methods for real-time log monitoring using either an enumerable approach or a callback-based approach with cancellation support. ```csharp using AdvancedSharpAdbClient; using AdvancedSharpAdbClient.Logs; AdbClient adbClient = new AdbClient(); DeviceData device = adbClient.GetDevices().First(); // Method 1: Enumerable log reading foreach (LogEntry entry in adbClient.RunLogService(device, LogId.Main, LogId.System)) { if (entry is AndroidLogEntry androidLog) { Console.WriteLine($"[{androidLog.TimeStamp}] {androidLog.Priority}/{androidLog.Tag}: {androidLog.Message}"); } } // Method 2: Callback-based log reading with cancellation bool isCancelled = false; adbClient.RunLogService(device, entry => { if (entry is AndroidLogEntry log) { Console.WriteLine($"{log.Priority}/{log.Tag}: {log.Message}"); if (log.Message.Contains("FATAL")) { isCancelled = true; } } }, in isCancelled, LogId.Main, LogId.Events, LogId.Crash); ``` -------------------------------- ### Screenshot Capture Source: https://context7.com/sharpadb/advancedsharpadbclient/llms.txt Capture device screen framebuffer as an image for testing, debugging, or automation purposes. ```APIDOC ## Screenshot Capture API ### Description Provides functionality to capture the screen framebuffer of an Android device. ### Methods #### Get Framebuffer (Synchronous) Captures the device screen framebuffer synchronously. - **Endpoint**: Not applicable (uses AdbClient instance) - **Method**: `adbClient.GetFrameBuffer(DeviceData device)` - **Parameters**: - `device` (DeviceData) - Required - The target device. - **Returns**: `Framebuffer` - An object containing framebuffer information and pixel data. #### Get Framebuffer (Asynchronous) Captures the device screen framebuffer asynchronously. - **Endpoint**: Not applicable (uses AdbClient instance) - **Method**: `adbClient.GetFrameBufferAsync(DeviceData device, CancellationToken cancellationToken)` - **Parameters**: - `device` (DeviceData) - Required - The target device. - `cancellationToken` (CancellationToken) - Required - Token to signal cancellation. - **Returns**: `Task` - A task that completes with the framebuffer object. #### Create Framebuffer Creates a reusable Framebuffer object for multiple captures. - **Endpoint**: Not applicable (uses AdbClient instance) - **Method**: `adbClient.CreateFramebuffer(DeviceData device)` - **Parameters**: - `device` (DeviceData) - Required - The target device. - **Returns**: `Framebuffer` - A Framebuffer object ready for capture. ### Request Example (Synchronous Capture) ```csharp Framebuffer framebuffer = adbClient.GetFrameBuffer(device); Console.WriteLine($"Screenshot: {framebuffer.Header.Width}x{framebuffer.Header.Height}"); Console.WriteLine($"Color format: {framebuffer.Header.ColorSpace}"); // Access raw pixel data byte[] pixels = framebuffer.Data; // Convert to Image using System.Drawing or other library // Image image = framebuffer.ToImage(); ``` ### Request Example (Asynchronous Capture) ```csharp Framebuffer asyncBuffer = await adbClient.GetFrameBufferAsync(device, CancellationToken.None); ``` ### Request Example (Reusable Framebuffer) ```csharp Framebuffer reusableBuffer = adbClient.CreateFramebuffer(device); reusableBuffer.Refresh(); // Capture // ... process image ... reusableBuffer.Refresh(); // Capture again ``` ### Response Example (Framebuffer Header) ```json { "Width": 1080, "Height": 1920, "Stride": 4320, "Format": "RGBA_8888", "ColorSpace": "sRGB" } ``` ``` -------------------------------- ### Connect to Android Device using AdbClient Source: https://github.com/sharpadb/advancedsharpadbclient/blob/main/README.md Initializes an AdbClient instance and connects to an Android device over the network. It then retrieves a list of connected devices and selects the first one. This is a prerequisite for most device interaction operations. ```csharp static AdbClient adbClient; static DeviceData deviceData; static void Main(string[] args) { adbClient = new AdbClient(); adbClient.Connect("127.0.0.1:62001"); device = adbClient.GetDevices().FirstOrDefault(); // Get first connected device ... } ``` -------------------------------- ### File Transfer with SyncService Source: https://context7.com/sharpadb/advancedsharpadbclient/llms.txt The SyncService class enables file transfers between your PC and Android devices, including push, pull, and directory listing operations. ```APIDOC ## SyncService API ### Description Provides methods for transferring files to and from Android devices, listing directory contents, and getting file information. ### Methods #### Pull File Downloads a file from the device to the local machine. - **Endpoint**: Not applicable (uses SyncService instance) - **Method**: `service.Pull(string remotePath, Stream localStream, IProgress progress)` - **Parameters**: - `remotePath` (string) - Required - The path to the file on the Android device. - `localStream` (Stream) - Required - The local stream to write the downloaded file to. - `progress` (IProgress) - Optional - A callback to report transfer progress. #### Push File Uploads a file from the local machine to the device. - **Endpoint**: Not applicable (uses SyncService instance) - **Method**: `service.Push(Stream localStream, string remotePath, UnixFileStatus mode, DateTimeOffset timestamp, IProgress progress)` - **Parameters**: - `localStream` (Stream) - Required - The local stream to read the file from. - `remotePath` (string) - Required - The destination path on the Android device. - `mode` (UnixFileStatus) - Required - The file permissions for the uploaded file. - `timestamp` (DateTimeOffset) - Required - The modification timestamp for the uploaded file. - `progress` (IProgress) - Optional - A callback to report transfer progress. #### Get Directory Listing Lists the contents of a directory on the device. - **Endpoint**: Not applicable (uses SyncService instance) - **Method**: `service.GetDirectoryListing(string remotePath)` - **Parameters**: - `remotePath` (string) - Required - The path to the directory on the Android device. - **Returns**: `IEnumerable` - A collection of file statistics for items in the directory. #### Stat File Retrieves information about a file on the device. - **Endpoint**: Not applicable (uses SyncService instance) - **Method**: `service.Stat(string remotePath)` - **Parameters**: - `remotePath` (string) - Required - The path to the file on the Android device. - **Returns**: `FileStatistics` - An object containing file information. ### Request Example (Pull) ```csharp using (SyncService service = new SyncService(adbClient, device)) { using (FileStream localFile = File.Create(@"C:\Downloads\config.xml")) { service.Pull("/sdcard/Android/data/com.app/config.xml", localFile, progress => Console.WriteLine($"Download: {progress.ProgressPercentage:F1}%")); } } ``` ### Request Example (Push) ```csharp using (SyncService service = new SyncService(adbClient, device)) { using (FileStream localFile = File.OpenRead(@"C:\Files\data.json")) { service.Push( localFile, "/sdcard/Download/data.json", UnixFileStatus.DefaultFileMode, // 644 permission DateTimeOffset.Now, progress => Console.WriteLine($"Upload: {progress.ProgressPercentage:F1}%")); } } ``` ### Request Example (List Directory) ```csharp using (SyncService service = new SyncService(adbClient, device)) { IEnumerable files = service.GetDirectoryListing("/sdcard/Download/"); foreach (FileStatistics file in files) { Console.WriteLine($"{file.Path} - Size: {file.Size} bytes, Modified: {file.Time}"); } } ``` ### Request Example (Stat File) ```csharp using (SyncService service = new SyncService(adbClient, device)) { FileStatistics stat = service.Stat("/sdcard/Download/myfile.txt"); Console.WriteLine($"Size: {stat.Size}, Mode: {stat.FileMode}, Time: {stat.Time}"); } ``` ### Response Example (FileStatistics) ```json { "Path": "/sdcard/Download/myfile.txt", "Size": 1024, "Mode": "0644", "Time": "2023-10-27T10:00:00Z", "IsDirectory": false } ``` ``` -------------------------------- ### File Transfer (Upload/Download) using C# Source: https://github.com/sharpadb/advancedsharpadbclient/blob/main/README.md Provides C# code for downloading files from an Android device to the local machine and uploading files from the local machine to the device using the SyncService. Requires a SyncService instance and FileStream objects. ```cs void DownloadFile() { using (SyncService service = new SyncService(deviceData)) { using (FileStream stream = File.OpenWrite(@"C:\MyFile.txt")) { service.Pull("/data/local/tmp/MyFile.txt", stream, null); } } } void UploadFile() { using (SyncService service = new SyncService(deviceData)) { using (FileStream stream = File.OpenRead(@"C:\MyFile.txt")) { service.Push(stream, "/data/local/tmp/MyFile.txt", UnixFileStatus.DefaultFileMode, DateTimeOffset.Now, null); } } } ``` -------------------------------- ### Find UI Element by XPath with AdvancedSharpAdbClient Source: https://github.com/sharpadb/advancedsharpadbclient/blob/main/README.md Finds a UI element on an Android device screen using its XPath. This method allows for precise element identification. An optional TimeSpan can be provided to specify a maximum waiting time for the element to appear. ```csharp static DeviceClient deviceClient; static void Main(string[] args) { ... deviceClient = new DeviceClient(adbClient, deviceData); Element element = deviceClient.FindElement("//node[@text='Login']"); ... } ``` ```csharp Element element = deviceClient.FindElement("//node[@text='Login']", TimeSpan.FromSeconds(5)); ``` ```csharp Element[] element = deviceClient.FindElements("//node[@resource-id='Login']", TimeSpan.FromSeconds(5)); ``` -------------------------------- ### Click on UI Element Coordinates or by XPath Source: https://github.com/sharpadb/advancedsharpadbclient/blob/main/README.md Allows clicking on a UI element either by specifying its X and Y coordinates or by finding the element using its XPath. The Click() method on an Element object will throw an ElementNotFoundException if the element is not found. ```csharp static void Main(string[] args) { ... deviceClient.Click(600, 600); // Click on the coordinates (600;600) ... } ``` ```csharp static void Main(string[] args) { ... Element element = deviceClient.FindElement("//node[@text='Login']", TimeSpan.FromSeconds(3)); element.Click(); // Click on element by xpath //node[@text='Login'] ... } ``` ```csharp try { element.Click(); } catch (Exception ex) { Console.WriteLine($"Can't click on the element:{ex.Message}"); } ``` -------------------------------- ### Send Android Key Events Source: https://github.com/sharpadb/advancedsharpadbclient/blob/main/README.md Simulate key presses on the Android device using predefined key event constants. Refer to the Android developer documentation for a list of available key events. An InvalidKeyEventException is thrown if an invalid key event is provided. ```cs static void Main(string[] args) { ... deviceClient.SendKeyEvent("KEYCODE_TAB"); ... } ``` ```cs try { deviceClient.SendKeyEvent(null); } catch (Exception ex) { Console.WriteLine($"Can't send keyevent:{ex.Message}"); } ``` -------------------------------- ### Set ADB Encoding using C# Source: https://github.com/sharpadb/advancedsharpadbclient/blob/main/README.md Shows how to change the default encoding for ADB communication. The default is UTF8, but it can be modified using the AdbClient.SetEncoding method with a specified Encoding object. ```cs AdbClient.SetEncoding(Encoding.ASCII); ``` -------------------------------- ### Swipe Between Elements or Coordinates Source: https://github.com/sharpadb/advancedsharpadbclient/blob/main/README.md Perform swipe gestures between two UI elements or from one coordinate to another on the device screen. The duration of the swipe can be specified in milliseconds. This method may throw an ElementNotFoundException if a specified element does not exist. ```cs static void Main(string[] args) { ... Element first = deviceClient.FindElement("//node[@text='Login']"); Element second = deviceClient.FindElement("//node[@text='Password']"); deviceClient.Swipe(first, second, 100); // Swipe 100 ms ... } ``` ```cs static void Main(string[] args) { ... deviceClient.Swipe(600, 1000, 600, 500, 100); // Swipe from (600;1000) to (600;500) on 100 ms ... } ``` ```cs try { deviceClient.Swipe(0x2232323, 0x954, 0x9128, 0x11111, 200); ... deviceClient.Swipe(first, second, 200); } catch (Exception ex) { Console.WriteLine($"Can't swipe:{ex.Message}"); } ``` -------------------------------- ### Send Text to Device Input Fields Source: https://github.com/sharpadb/advancedsharpadbclient/blob/main/README.md Send text input to the focused element on the device. Cyrillic characters are not supported. Text can be sent directly or by first locating an element using XPath. An InvalidTextException is thrown if the provided text is invalid. ```cs static void Main(string[] args) { ... deviceClient.SendText("text"); // Send text to device ... } ``` ```cs static void Main(string[] args) { ... deviceClient.FindElement("//node[@resource-id='Login']").SendText("text"); // Send text to the element by xpath //node[@resource-id='Login'] ... } ``` ```cs try { deviceClient.SendText(null); } catch (Exception ex) { Console.WriteLine($"Can't send text:{ex.Message}"); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.