Giter Site home page Giter Site logo

sharpadb / advancedsharpadbclient Goto Github PK

View Code? Open in Web Editor NEW
177.0 177.0 51.0 6.56 MB

AdvancedSharpAdbClient is a .NET library that allows .NET, Mono and Unity applications to communicate with Android devices. It's improved version of SharpAdbClient.

Home Page: https://sharpadb.github.io

License: Apache License 2.0

C# 100.00%
adb android csharp dotnet mono unity uwp

advancedsharpadbclient's People

Contributors

cugljd avatar ilamp avatar sdijoseph avatar shamork avatar tangent-90 avatar toofderling avatar wherewhere avatar yatink-ci avatar yungd1plomat avatar ztamas83 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

advancedsharpadbclient's Issues

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in AdvancedSharpAdbClient.dll

What can we do for you?

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in AdvancedSharpAdbClient.dll

Additional information: Could not load file or assembly 'System.Runtime.InteropServices.RuntimeInformation, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

image

use platform
.NET Framework 4.5.2

We need a better documentation for the library

i like this project and i had been using recently to do some stuff with phones, but actually we need a better readable documentation because the library has a ton of stuff. But we lose a lot of time trying to understand how of some of the funtionality works with it because there is no documentation avalaible for it.

Remove support for EOL .NET Packages

Describe your feature request

Remove support for EOL .NET Packages.

EOL Versions List: TBD

How important is this to you?

Important

Describe the solution you'd like

Support for EOL .NET versions is removed and code specific to those versions is removed.

Describe alternatives you've considered

No response

Additional context

No response

deviceClient.StartApp("com.android.app"); doesn't work

Describe the bug

HI! I have updated package from 2.5.8 to 3.0.9 buy found that deviceClient.StartApp("com.android.app"); doesn't open apk on smartphone There are no errors in log. I use NET Framework 4.8

Steps to reproduce the bug

  1. Install facebook apk
  2. deviceClient.StartApp("com.facebook.katana");

Expected behavior

No response

Screenshots

No response

NuGet package version

3.0.9

.NET Platform

.NET Framework 4.8.x

Platform type

Windows

System version

windows 10 pro

IDE

Visual Studio 2022

Additional context

No response

Getting Image screen shot and data array wrong size

Describe the bug

1.Any Time I try to create either a refreshable buffer from client or try to create a one time screen shoot I get a "cannot read past end of stream error." I tracked this down to being for the reader. When the project gets the header it doesn't set properly in FrameBuffer loading.
2.There was also an issue where the initlized data array from arraypool was renting a little under twice the size needed. This would cause a issue on Header.ToImage(Data) to say image buffer larger then expected.

Steps to reproduce the bug

using code as documented in start up.

Expected behavior

No response

Screenshots

No response

NuGet package version

No response

.NET Platform

.NET 6

Platform type

Windows

System version

2.5.2

IDE

Visual Studio 2022

Additional context

I was able to make a copy of data and fix the issues. I will be submit detailed spots where it could be fixed later. Until then I am using a copy from the class in its own function in my code to get screen shot.

FindElements return null

Hey.
I use real phones.
In my case FindElement\FindElements alwways return null.
I tried:

client.FindElements(device, "//node[@class='android.widget.ImageView']");
client.FindElements(device, "//node");
client.FindElements(device, "//android.widget.ImageView");

Get App Status Support

Describe your feature request

This allows support checking if an app is running, stopped or running in background.

How important is this to you?

Important

Describe the solution you'd like

No response

Describe alternatives you've considered

No response

Additional context

No response

Default port doubling

Describe the bug

Somehow calling ConnectAsync overload without port doubles default port

Steps to reproduce the bug

Calling string result = await client.ConnectAsync("127.0.0.1", cancellationToken: token);
will produce unable to connect to 127.0.0.1:5555:5555

Expected behavior

No response

Screenshots

No response

NuGet package version

2.5.5

.NET Platform

.NET 7

Platform type

Windows

System version

No response

IDE

No response

Additional context

No response

Screenshot image is offset

On my tests, using :

Task<Image> task = client.GetFrameBufferAsync(device, CancellationToken.None);
Image img = task.Result;

I was getting this offset on the image :
2021-10-16 00 44 52 538 - rand324388985
image

after some hours I found the problem was here
https://github.com/yungd1plomat/AdvancedSharpAdbClient/blob/a0f04e62b332f1c31d4aadca15c26aa2fff1c83f/AdvancedSharpAdbClient/ColorData.cs#L31
this extra (and not used) variable is increasing the header size used here
https://github.com/yungd1plomat/AdvancedSharpAdbClient/blob/a0f04e62b332f1c31d4aadca15c26aa2fff1c83f/AdvancedSharpAdbClient/Framebuffer.cs#L50-L51

Even after removing that variable there was still 1px column offset. Manually set the size to 52 solved the problem completely.
this.headerData = new byte[52];

An error occurred while receiving xml: ERROR: null root node returned

Describe the bug

I always find this bug when searching for elements

Dim Elspgsuara = Adb.FindElement("//node[@text='Mulai panggilan suara?']") 

for the device
image

how to solve it if node is null

Steps to reproduce the bug

Dim elEndC = Adb.FindElement($"//node[@resource-id='com.{whatsapp}:id/footer_end_call_btn']")
If (elEndC Is Nothing) Then
    Dim Elspgsuara = Adb.FindElement("//node[@text='Mulai panggilan suara?']") 'bar ic VOICE

    If Not (Elspgsuara Is Nothing) Then
        Thread.Sleep(500)
        KlikTouch("PAG", whatsapp)
    End If

    Dim Elstpaggil = Adb.FindElement("//node[@text='Pilih tipe panggilan']") 'bar ic VOICE

    If Not (Elstpaggil Is Nothing) Then
        Thread.Sleep(500)
        KlikTouch("PS1", whatsapp)
    End If
End If

Expected behavior

No response

Screenshots

No response

NuGet package version

Latest Source

.NET Platform

.NET Framework 4.5.x

Platform type

Windows

System version

windows 10

IDE

Visual Studio 2015

Additional context

No response

Does it work with MAUI?

Describe your question

I would like to know if the package works with MAUI for the Android and iOS platforms?

Thanks in advance. ;)

Planned release?

Hi! Do you have a plan in mind for the next release? There are quite some changes after the latest release.

ShellCommandUnresponsiveException while DumpScreenAsync

Describe the bug

Getting this exception only while this screen (Look screenshots section).
I think that the timer is to blame for everything, because when it expires, the exception stops appearing.
The worst part of all this is that after getting this exception at least once, it most likely breaks something and I get this exception regardless of whether I closed this page with a timer or not.

I'm using virtual machine with android 9.
App on screenshot: Official Telegram mobile client

System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
   at System.Xml.XmlTextReaderImpl.Throw(Exception e)
   at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
   at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
   at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
   at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
   at System.Xml.XmlDocument.Load(XmlReader reader)
   at System.Xml.XmlDocument.LoadXml(String xml)
   at AdvancedSharpAdbClient.AdbClient.DumpScreenAsync(DeviceData device, CancellationToken cancellationToken)

Steps to reproduce the bug

Try to DumpScreenAsync while "Enter code" page.
This is very complicated to reproduce this bug by yourself, it's costs 0.34$ each time :)
But I'm all yours.

Expected behavior

No response

Screenshots

image

NuGet package version

2.5.5

.NET Platform

.NET 7

Platform type

Windows

System version

Windows 11 Pro 22H2 22621.1413

IDE

Other

Additional context

No response

Announcing to the WinRT package of AdvancedSharpAdbClient

Announcing

We have packaged this project into winrt. With the winrt version, we can use it in cpp/winrt and other projects. You can find the winrt version in winrt branch.

How to use it

There are two way to reference it.

  • Reference to the project directly

Fork this repository and change the branch to winrt.

If your project is face to uwp, add this to your .vcproj

<ProjectReference Include="\path\to\AdvancedSharpAdbClient.WinRT.csproj">
  <Project>{083cdc04-9cc2-46e4-84c2-55b645be9d50}</Project>
  <SetTargetFramework>TargetFramework=uap10.0</SetTargetFramework>
</ProjectReference>

If your project is face to desktop, add this to your .vcproj

<ProjectReference Include="\path\to\AdvancedSharpAdbClient.WinRT.csproj">
  <Project>{083cdc04-9cc2-46e4-84c2-55b645be9d50}</Project>
  <SetTargetFramework>TargetFramework=net6.0-windows10.0.17763.0</SetTargetFramework>
</ProjectReference>
  • Reference to the nuget package

Download AdvancedSharpAdbClient.WinRT.zip.

Unzip it into nupkgs folder of the root path of your project
image

Create nuget.config into the root path of your project and add

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="Offline Nugets" value="nupkgs" />
  </packageSources>
</configuration>

Open the manager of nuget and you will find it. Just install it like a normal nuget.
image

After that, if your project is not packaged into appx or misx, remember to create ProjectName.exe.manifest in the root of your project to register winrt class.

<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
  <assemblyIdentity version="1.0.0.0" name="ProjectName"/>
  <file name="WinRT.Host.dll">
    <activatableClass
      name="AdvancedSharpAdbClient.WinRT.AdbClient"
      threadingModel="both"
      xmlns="urn:schemas-microsoft-com:winrt.v1" />
    <activatableClass
      name="AdvancedSharpAdbClient.WinRT.AdbCommandLineClient"
      threadingModel="both"
      xmlns="urn:schemas-microsoft-com:winrt.v1" />
    <activatableClass
      name="AdvancedSharpAdbClient.WinRT.AdbServer"
      threadingModel="both"
      xmlns="urn:schemas-microsoft-com:winrt.v1" />
    <activatableClass
      name="AdvancedSharpAdbClient.WinRT.AdbServerFeatures"
      threadingModel="both"
      xmlns="urn:schemas-microsoft-com:winrt.v1" />
    <activatableClass
      name="AdvancedSharpAdbClient.WinRT.AdbSocket"
      threadingModel="both"
      xmlns="urn:schemas-microsoft-com:winrt.v1" />
    <activatableClass
      name="AdvancedSharpAdbClient.WinRT.CrossPlatformFunc"
      threadingModel="both"
      xmlns="urn:schemas-microsoft-com:winrt.v1" />
    <activatableClass
      name="AdvancedSharpAdbClient.WinRT.DateTimeHelper"
      threadingModel="both"
      xmlns="urn:schemas-microsoft-com:winrt.v1" />
    <activatableClass
      name="AdvancedSharpAdbClient.WinRT.DeviceMonitor"
      threadingModel="both"
      xmlns="urn:schemas-microsoft-com:winrt.v1" />
    <activatableClass
      name="AdvancedSharpAdbClient.WinRT.Factories"
      threadingModel="both"
      xmlns="urn:schemas-microsoft-com:winrt.v1" />
    <activatableClass
      name="AdvancedSharpAdbClient.WinRT.SyncCommandConverter"
      threadingModel="both"
      xmlns="urn:schemas-microsoft-com:winrt.v1" />
    <activatableClass
      name="AdvancedSharpAdbClient.WinRT.SyncService"
      threadingModel="both"
      xmlns="urn:schemas-microsoft-com:winrt.v1" />
    <activatableClass
      name="AdvancedSharpAdbClient.WinRT.TcpSocket"
      threadingModel="both"
      xmlns="urn:schemas-microsoft-com:winrt.v1" />
    <activatableClass
      name="AdvancedSharpAdbClient.WinRT.DeviceCommands.LinuxPath"
      threadingModel="both"
      xmlns="urn:schemas-microsoft-com:winrt.v1" />
    <activatableClass
      name="AdvancedSharpAdbClient.WinRT.DeviceCommands.PackageManager"
      threadingModel="both"
      xmlns="urn:schemas-microsoft-com:winrt.v1" />
    <activatableClass
      name="AdvancedSharpAdbClient.WinRT.Logs.LogReader"
      threadingModel="both"
      xmlns="urn:schemas-microsoft-com:winrt.v1" />
  </file>
</assembly>

Pulling folder content

What can we do for you?

this is my code to pull the dcim image on the android main storage:

async Task DownloadFiles()
{
   SyncService service = new SyncService(device);

   string folderPath = Environment.CurrentDirectory + "/downloaded_files";

   // Ensure the target folder exists, create it if needed
   if (!Directory.Exists(folderPath))
   {
       Directory.CreateDirectory(folderPath);
   }

   string source = "/sdcard/dcim";
   var files = await service.GetDirectoryListingAsync(source);

   // Download each file and save it to the local folder
   foreach (var file in files)
   {
       service = new SyncService(device);

       string localFilePath = Path.Combine(folderPath, file.Path);

       using (FileStream stream = File.OpenWrite(localFilePath))
       {
           string path = source + "/" + file.Path;        
           await service.PullAsync(path, stream);
       }
   }
}

I'm getting this error:
Failed to pull '/sdcard/dcim/Camera'. read failed: Is a directory

I can't specify in advance the full path, "/sdcard/dcim/camera" because my program need to pull the entire "dcim" content,and it might be dynamic content,and contain many other folders inside....is there any way to pull is like using the simple shell command "adb pull /sdcard/dcim"(which would do the work perfectly)?
Thanks in advance guys!

Configure workflow for auto releasing

Describe your feature request

Need 2 workflows:

  1. For pull requests on main branch - build, test and upload artifacts
  2. For push on main branch - build, test and push to nuget

Example

How important is this to you?

Important

Describe the solution you'd like

No response

Describe alternatives you've considered

No response

Additional context

No response

The server returned an invalid sync response 0 when trying to pull.

Describe the bug

I'm using the adb server included with the Android platform tools.

Android Debug Bridge version 1.0.41
Version 33.0.3-8952118

Host project is .NET 4.8.1, code is as follows

var adb = new AdbClient();
var devices = (await adb.GetDevicesAsync()).ToArray();

if (devices.Length > 0)
{
    var device = devices[0];

    var client = device.CreateDeviceClient();

    var receiver = new ConsoleOutputReceiver();

    await adb.ExecuteRemoteCommandAsync("pm list packages -f -3", device, receiver);

    var pmOutput = receiver.ToString();

    var match = Regex.Match(pmOutput, @"^package:(.*?)=com.beatgames.beatsaber\r?$", RegexOptions.Multiline);

    if (!match.Success)
    {
        MessageBox.Show("Beat Saber not found", "Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error);

        return;
    }

    var beatSaberPath = match.Groups[1].ToString();

    using (var service = new SyncService(adb, device))
    {
        var files = await service.GetDirectoryListingAsync("/sdcard/Android/obb/com.beatgames.beatsaber");
        var dlcTemp = new EasyTempFolder("dlc", Program.TempFolder);
        var apkTemp = new EasyTempFolder("apk", Program.TempFolder);

        Program.Disposables.Add(dlcTemp);
        Program.Disposables.Add(apkTemp);

        var localApkPath = Path.Combine(apkTemp, "beatsaber.apk");

        using (var localFile = File.Create(localApkPath))
        {
            await service.PullAsync(beatSaberPath, localFile, null);
        }
    }
}

From my understanding of the documentation, this should work, but it doesn't. Pulling with adb.exe does however.

Steps to reproduce the bug

Use provided code with Android emulator.

Expected behavior

No response

Screenshots

No response

NuGet package version

3.1.10

.NET Platform

.NET Framework 4.8.x

Platform type

Windows

System version

No response

IDE

Visual Studio 2022

Additional context

No response

An error occurred while reading a response from ADB: device not found

Доброго времени суток, использую библиотеку для автоматизации эмулятора Memu, переписал код нахождения IP эмулятора Memu (порты начинаются на 215), но программа работает через раз иногда с разными ошибками, но с примерно таким смыслом - An error occurred while reading a response from ADB: device '127.0.0.1:21503' not found. Хотя в этот же момент если через консоль вывести список девайсов с помощью adb, то получаю такую картину:
adb.exe devices
List of devices attached
127.0.0.1:21503 device

Следовательно IP устройств я получаю корректно, да и подключение к ним работает в принципе корректно только через раз.
В чем может быть проблема?

What's the best way to touch->drag->wait->drag->wait->drop

What can we do for you?

Hello guys,
It's clear on the title, I want to drag it to a location and wait there without untouch fired and continue to drag another location.

I tried something like:

await _adbClient.ExecuteRemoteCommandAsync($"sendevent /dev/input/event3 3 57 122", DeviceData, receiver, CancellationToken.None);
await _adbClient.ExecuteRemoteCommandAsync($"sendevent /dev/input/event3 1 330 1", DeviceData, receiver, CancellationToken.None);
await _adbClient.ExecuteRemoteCommandAsync($"sendevent /dev/input/event3 3 53 203", DeviceData, receiver, CancellationToken.None);
await _adbClient.ExecuteRemoteCommandAsync($"sendevent /dev/input/event3 3 54 293", DeviceData, receiver, CancellationToken.None);
await _adbClient.ExecuteRemoteCommandAsync($"sendevent /dev/input/event3 0 0 0", DeviceData, receiver, CancellationToken.None);

But somehow I'm unlucky today. Any advise on this?

Add split app support

Install split apps need install-multiple command. But I didn't find a way to execute this command. Using ExecuteRemoteCommand
it say /system/bin/sh: install-multiple: inaccessible or not found. Could add support for Split APK?

Async listen to client

What can we do for you?

Hi, thanks for your aweomse library!
I need some help in async listening to the device connection... this is my code:

public MainWindow()
{
    InitializeComponent();

    StartAdbServer();

    var deviceMonitor = new DeviceMonitor(new AdbSocket("127.0.0.1", 62001));
    deviceMonitor.DeviceConnected += OnDeviceConnected;
    deviceMonitor.Start();
}

private void StartAdbServer()
{
    if (!AdbServer.Instance.GetStatus().IsRunning)
    {
        AdbServer server = new AdbServer();
        StartServerResult result = server.StartServer(@"C:\Users\Itamar\AppData\Local\Android\Sdk\platform-tools\adb.exe", false);
        if (result != StartServerResult.Started)
        {
            MessageBox.Show("Can't start adb server");
        }
        else
        {
            MessageBox.Show("started adb server");
        }
    }
}

But I'm getting error with that....
No connection could be made because the target machine actively refused it.

And there is device connected indeed...can you give me a clue about what I need to do?

Issue when using "AdbClient.Connect" with WPF application

Describe your question

Hello,

If I use the following piece of code in a Winforms app, the call/process takes <10ms but the same code when used in a WPF application (bare bones app), the same call takes 2600ms. Any idea why that is?

var result = adbclient.Connect("192.168.1.111");

or even

var result = adbclient.ConnectAsync("192.168.1.111");

Screenshot error report

Describe the bug

static async void Main(string[] args)
{
    ...
    System.Drawing.Image img = client.GetFrameBufferAsync(device, CancellationToken.None).GetAwaiter().GetResult(); // synchronously
    ...
    System.Drawing.Image img = await client.GetFrameBufferAsync(device, CancellationToken.None); // asynchronously
    ...
}

System.IO.EndOfStreamException Cannot read outside the end of the stream

Steps to reproduce the bug

An error is reported when the screenshot function is called

Expected behavior

No response

Screenshots

No response

NuGet package version

2.5.4

.NET Platform

.NET Framework 4.6.x

Platform type

Windows

System version

No response

IDE

Visual Studio 2017

Additional context

No response

ExtendedSocketException

Describe the bug

After a long (about two hours) work with 6 devices at the same time, everything stops working and exceptions begin to be thrown:

System.Net.Internals.SocketExceptionFactory+ExtendedSocketException: An operation on a socket could not be performed
because the system lacked sufficient buffer space or because a queue was full. 127.0.0.1:5037

Please tell me what could be the solution to my problem?

Steps to reproduce the bug

  1. Long work with the library

Expected behavior

No response

Screenshots

No response

NuGet package version

2.5.7

.NET Platform

.NET 7

Platform type

Windows

System version

ReviOS 11 23.03

IDE

Rider 2023

Additional context

No response

SendText works wierdly on special characters

Describe the bug

Is that expected we need to escape special characters ? or may be better library should do itself to be safer, right ?

Steps to reproduce the bug

Sub Main()
    Dim client = New AdbClient()
    client.Connect("emulator-5554")
    Dim device = client.GetDevices().FirstOrDefault()
    Console.WriteLine(device.Model)

    PassElement.ClearInput()
    PassElement.SendText("#")     'Result = AdvancedSharpAdbClient.Exceptions.InvalidTextException: Text contains invalid symbols
    PassElement.SendText("\#")    'Result = #
    PassElement.SendText("$")     'Result = $
    PassElement.SendText("a$a")   'Result = a
    PassElement.SendText("a\$a")  'Result = a$a
End Sub

Expected behavior

No response

Screenshots

No response

NuGet package version

Latest Source

.NET Platform

.NET Framework 4.6.x

Platform type

Windows

System version

windows 10

IDE

Visual Studio 2017

Additional context

No response

Is there a way of seeing if a FileStatisitcs result is a dir or file?

I can't see an easy way of seeing this from the provided stats. Is there a way to see if a read statistics result is a file or directory?

I did have a idea of working it out by running everything through GetDirectoryListing and checking the result but wanted to check before I went down that path.

Just Need help.

I am just learning how to use this, I am trying to figure out how to zoom in and out using this. Basically multi touch operation.

Also, if there is a place where I can review multiple examples of AdvanceSharpAdbClient, I would love to review them so I can learn all the different actions I can take.

My project revolves around automation of form entries within Apps. I have to be able to scroll and zoom in and out, and type text.

Can Screen Capture be improved?

Describe your feature request

Is it possible to capture screen devices faster?Feature title

static async void Main(string[] args)
{
    ...
    System.Drawing.Image img = client.GetFrameBufferAsync(device, CancellationToken.None).GetAwaiter().GetResult();
    ...
}

Specifically, it currently takes 180 ~ 200ms for 1 screen capture

How important is this to you?

Nice-to-have

Describe the solution you'd like

No response

Describe alternatives you've considered

No response

Additional context

No response

Add Tests and Documentation for App/Package Status

Describe your feature request

Add Tests and Documentation for App/Package Status

How important is this to you?

Important

Describe the solution you'd like

No response

Describe alternatives you've considered

No response

Additional context

No response

PackageManager.InstallPackage throw exception

.net :4.7.2
file version:1.3.0.0
nuget version:2.5.1

when i use InstallPackage,
always reporting an exception

AdvancedSharpAdbClient.Exceptions.AdbException:“missing , in ID_SEND_V1”

code:

public string InstallApp(string appPath)
{
    PackageManager manager = new PackageManager(this.client, device);
            
    manager.InstallPackage(appPath, reinstall: true);
    return "Success";
}

Unable to read beyond the end of the stream.

Describe the bug

Please leave this open I'm still looking into this. So far I'm getting this error message on only one device. I want to be able to reproduce it and will add more information as I have it.

at System.IO.BinaryReader.InternalRead(Int32 numBytes)
at System.IO.BinaryReader.ReadUInt32()
at AdvancedSharpAdbClient.FramebufferHeader.Read(Byte[] data)
at AdvancedSharpAdbClient.Framebuffer.RefreshAsync(CancellationToken cancellationToken)
at AdvancedSharpAdbClient.AdbClient.GetFrameBufferAsync(DeviceData device, CancellationToken cancellationToken)
at Device.TakeScreenshot() in E:***Adb.cs:line 26

Steps to reproduce the bug

TODO

Expected behavior

No response

Screenshots

No response

NuGet package version

None

.NET Platform

No response

Platform type

No response

System version

No response

IDE

No response

Additional context

No response

DumpScreen relies on Xml string not containing "ERROR" inside

Describe the bug

If you call DumpScreen(DeviceData device) on AdvancedAdbClient it'll return null if the dumped Xml contains "ERROR" anywhere inside, even if it's just text in an element

Steps to reproduce the bug

  1. On device open anything that contains text "ERROR"
  2. Call DumpScreen
  3. It returns null

Expected behavior

Get an XmlDocument

Screenshots

No response

NuGet package version

2.5.2

.NET Platform

.NET 6

Platform type

Windows

System version

Windows 10

IDE

Other

Additional context

Does this check really have to be like this? Maybe it can be changed to Equals instead of Contains or even simply be removed

DeviceMonitor Dispose Error

Describe the bug

var deviceMonitor = new DeviceMonitor(new AdbSocket(new IPEndPoint(IPAddress.Loopback, AdbClient.AdbServerPort)));
deviceMonitor.DeviceDisconnected += DeviceMonitor_DeviceDisconnected;
deviceMonitor.Start();
...
deviceMonitor.DeviceDisconnected -= DeviceMonitor_DeviceDisconnected;
deviceMonitor.Dispose(); // ExceptionOccurred
deviceMonitor = null;

If Dispose() is not used; There is nothing unusual about that, but it should be necessary
Then ADB is not closed and can only be closed by a manual lookup process. Without adbServer.Shutdown(); Such function

Steps to reproduce the bug

Run deviceMonitor and try to free it.

Expected behavior

System.OperationCanceledException"

NuGet package version

2.5.7

.NET Platform

.NET 7

Platform type

Windows

IDE

Visual Studio 2022

How to construct a DeviceClient

What can we do for you?

I want to listen to a device connection,but I don't know how to obtain a "DeviceClient" object,so I can execute actions on it...I have the DeviceData but it doesn't help me much...

public async Task Start()
      {
          StartServerResult startServerResult = await AdbServer.Instance.StartServerAsync(@"C:\Users\laptop\AppData\Local\Android\Sdk\platform-tools\adb.exe", false, CancellationToken.None);
          Trace.WriteLine(startServerResult); // result is already running

 
          DeviceMonitor deviceMonitor = null;

          deviceMonitor = new DeviceMonitor(new AdbSocket(new IPEndPoint(IPAddress.Loopback, AdbClient.AdbServerPort)));
          deviceMonitor.DeviceConnected += (sender, e) =>

          {
              Trace.WriteLine($"Device connected: {e.Device}");

              //need to obtain a DeviceClient object,to execute a swipe method.
           

          };
          deviceMonitor.DeviceDisconnected += (sender, e) => Trace.WriteLine($"Device disconnected: {e.Device}");
          deviceMonitor.DeviceChanged += (sender, e) => Trace.WriteLine($"Device state changed: {e.Device} {e.OldState} -> {e.NewState}");

          await deviceMonitor.StartAsync();

          // Additional code if needed
      }

Need help for Implicit and Explicit wait in AdvancedSharpAdbClient

What can we do for you?

While working with AdvancedSharpAdbClient , for android element automation, sometimes few elements not loaded properly, or the elements configuration not matches, so there may be the any reason, so for that we want to wait for the element will appear or something like wait.until(ExpectedConditions.visibilityOf()), so for that we want explicit wait. So I request if anything is already then it will be good or plz suggest the solution for this.
Advance Thanking you...

logcat is very slow

Describe the bug

Here is the code:

// 打开Logcat
private void menuItemLogcatOpen_Click(object sender, EventArgs e) {
    if (!star.AdbHelper.isDeviceSelected()) { formLog.showConsoleWnd(); star.UILogger.logOnConsole("设备未连接", star.UILogger.LogLevel.warning); return; }
    formLog.showLogcatWnd();

    try {
        string shellCmd = "logcat";
        star.UILogger.logOnConsole(shellCmd, star.UILogger.LogLevel.info);
        cancellationTokenSource = new();
        taskLogcat = star.AdbHelper.shellCmdAsync(shellCmd, new star.AdbShellLogcatReceiver(context), cancellationTokenSource.Token);
        star.UILogger.logOnConsole("—————————————————————\n", star.UILogger.LogLevel.verbose);
    } catch (Exception ex) {
        star.UILogger.logOnConsole(ex.ToString(), star.UILogger.LogLevel.error);
    }
}

AdbShellLogcatReceiver is a class that receives callback logs and echoes them:

class AdbShellLogcatReceiver : IShellOutputReceiver {
    private readonly SynchronizationContext context;   //获取UI线程同步上下文

    public AdbShellLogcatReceiver(SynchronizationContext context) {
        this.context = context;
    }
    bool IShellOutputReceiver.ParsesErrors { get; }

    void IShellOutputReceiver.AddOutput(string line) {
        UILogger.logOnLogcat(line, UILogger.LogLevel.verbose, context, false); //异步时可能文本量较大,加速用
    }

    void IShellOutputReceiver.Flush() {
    }
}

It takes a long time to obtain and display the logs. How can I improve it?

Steps to reproduce the bug

Refer to the code above

Expected behavior

No response

Screenshots

No response

NuGet package version

2.5.7

.NET Platform

.NET 7

Platform type

No response

System version

No response

IDE

No response

Additional context

No response

adb devices

What can we do for you?

Dear yungd1plomat,

My name is SlappyZ, and I am an avid user of ADB (Android Debug Bridge). Lately, I've been attempting to execute the "adb devices" command on my system to retrieve a list of connected devices and emulators.

I have been trying to check the Nox Player instances on my system, as I use multiple Nox instances for my development and testing purposes. The "adb devices" command should typically provide a list of connected devices and emulators along with their respective serial numbers, but instead, I'm not getting any response.

Here is some information about my system:

Operating System: [Windows 10]
ADB Version: [latest]
Nox Player Version: [7.0.5.7]

I have also ensured that the ADB drivers are properly installed and that my system recognizes the Nox Player instances. Other ADB commands seem to be working, but specifically, the "devices" command is not producing any output.

Could you kindly assist me in determining whether this is a known issue or if there might be an error or bug in my ADB installation? Are there any additional steps I can take to diagnose and resolve the problem?

Thank you in advance for your help and support.

Best regards,
[Slappy]

Pushing/pulling files from the device

What can we do for you?

I'm using the following code:

void DownloadFile()
{
    using (SyncService service = new SyncService(device))
    {
        string path = Environment.CurrentDirectory + @"\test.txt";
        using (FileStream stream = File.OpenWrite(path))
        {
            service.PullAsync("/data/local/tmp/a.txt", stream, null);
        }
    }
}

void UploadFile()
{
    using (SyncService service = new SyncService(device))
    {
        string path = Environment.CurrentDirectory + @"\test.txt";
        using (FileStream stream = File.OpenRead(path))
        {
            service.PushAsync(stream, "/data/local/tmp/a.txt", 777, DateTimeOffset.Now, null);
        }
    }
}

But nothing happends... Neither the "UploadFile" method works, nor the other.
What I'm doing wrong..?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.