AdvancedSharpAdbClient

repository·main·Indexed 43 days ago

https://github.com/sharpadb/advancedsharpadbclient

A .NET library providing a high-level implementation of the Android Debug Bridge (ADB) protocol. It enables .NET developers to automate Android devices, interact with UI elements via XPath, manage applications, perform file transfers via SyncService, and execute remote shell commands without manually parsing CLI output from adb.exe.

Tokens
2.5K
Snippets
13
Records
13
Agent score
5%

What's inside AdvancedSharpAdbClient

  1. Start the ADB server

    main

    AdvancedSharpAdbClient communicates with Android devices via the adb.exe server process. You must ensure the server is running before connecting to devices. You can start it programmatically using AdbServer.StartServer by providing the path to your adb.exe.

    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");
        }
    }
  2. Connect to an Android device

    main

    To interact with a device, initialize an AdbClient, connect to the ADB server address (e.g., 127.0.0.1:5037), and retrieve a DeviceData object from the connected devices list.

    static AdbClient adbClient;
    static DeviceData deviceData;
    
    static void Main(string[] args)
    {
        adbClient = new AdbClient();
        adbClient.Connect("127.0.0.1:62001");
        deviceData = adbClient.GetDevices().FirstOrDefault(); // Get first connected device
        ...
    }
  3. Execute remote shell commands

    main

    Run shell commands on the Android device using ExecuteRemoteCommand or ExecuteRemoteCommandAsync. Use a ConsoleOutputReceiver to capture the command output.

    ConsoleOutputReceiver receiver = new ConsoleOutputReceiver();
    // Synchronous
    adbClient.ExecuteRemoteCommand("echo Hello, World", device, receiver);
    // Asynchronous
    await adbClient.ExecuteRemoteCommandAsync("echo Hello, World", device, receiver, default);
  4. Send text and clear input

    main

    Send text to the device using SendText. The text field must be in focus. You can send text to the device generally, or target a specific Element which will click it first. Note: Cyrillic characters are not supported. To clear text, use ClearInput(int maxChars) for a recommended approach, or element.ClearInput() which may be less stable.

    // Send text to device (field must be in focus)
    deviceClient.SendText("text");
    
    // Send text to a specific element
    deviceClient.FindElement("//node[@resource-id='Login']").SendText("text");
    
    // Clear input (recommended: specify max characters to erase)
    deviceClient.ClearInput(25);
  5. Transfer files via SyncService

    main

    Use SyncService to push files to the device or pull files from the device. This is useful for moving data between the host and the Android filesystem.

    // Download file from device
    using (SyncService service = new SyncService(deviceData))
    {
        using (FileStream stream = File.OpenWrite(@"C:\MyFile.txt"))
        {
            service.Pull("/data/local/tmp/MyFile.txt", stream, null);
        }
    }
    
    // Upload file to device
    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);
        }
    }
  6. Capture screenshots and screen hierarchy

    main

    Retrieve the current screen state using GetFrameBuffer (for images) or DumpScreen (for XML hierarchy). GetFrameBuffer supports both synchronous and asynchronous calls.

    // Get screenshot (Sync/Async)
    Image img = adbClient.GetFrameBuffer(deviceData, CancellationToken.None);
    Image imgAsync = await adbClient.GetFrameBufferAsync(deviceData, CancellationToken.None);
    
    // Get XML hierarchy
    XmlDocument screen = deviceClient.DumpScreen();
  7. Get element attributes

    main

    Once an Element is found, you can access its properties via the Attributes dictionary. Common keys include text and bounds.

    Element element = deviceClient.FindElement("//node[@resource-id='Login']", TimeSpan.FromSeconds(3));
    string eltext = element.Attributes["text"];
    string bounds = element.Attributes["bounds"];
  8. Click on elements or coordinates

    main

    You can perform click actions either by specifying screen coordinates $(x, y)$ or by calling .Click() directly on an Element object found via XPath. Note that .Click() on an element will throw an ElementNotFoundException if the element is not present.

    // Click by coordinates
    deviceClient.Click(600, 600);
    
    // Click an element
    Element element = deviceClient.FindElement("//node[@text='Login']", TimeSpan.FromSeconds(3));
    try
    {
        element.Click();
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Can't click on the element:{ex.Message}");
    }
  9. Find elements using XPath

    main

    Use DeviceClient to find UI elements on the screen using XPath expressions. You can specify a timeout using a TimeSpan to wait for the element to appear.

    // Find a single element
    Element element = deviceClient.FindElement("//node[@text='Login']", TimeSpan.FromSeconds(5));
    
    // Find multiple elements
    Element[] elements = deviceClient.FindElements("//node[@resource-id='Login']", TimeSpan.FromSeconds(5));
  10. Send key events and system buttons

    main

    Simulate hardware key presses using SendKeyEvent with Android KeyEvent constants (e.g., "KEYCODE_TAB"). You can also use convenience methods for common system actions like ClickBackButton() and ClickHomeButton().

    // Send a specific key event
    deviceClient.SendKeyEvent("KEYCODE_TAB");
    
    // System buttons
    deviceClient.ClickBackButton();
    deviceClient.ClickHomeButton();
  11. Manage applications (Install/Uninstall/Start/Stop)

    main

    Use PackageManager or AdbClient to manage Android applications. Some operations may require Root access. You can install single APKs, multiple split APKs, or uninstall packages by name.

    // Using PackageManager
    PackageManager manager = new PackageManager(adbClient, deviceData);
    manager.InstallPackage(@"C:\path\to\package.apk");
    manager.InstallMultiplePackage(@"C:\path\to\base.apk", new[] { @"C:\path\to\split_1.apk" });
    
    // Using AdbClient directly
    using (FileStream stream = File.OpenRead("Application.apk"))
    {
        adbClient.Install(device, stream);
    }
    
    // App lifecycle
    deviceClient.StartApp("com.android.app");
    deviceClient.StopApp("com.android.app");