Giter VIP home page Giter VIP logo

madb's Introduction

build coverage NuGet
Build Status codecov.io NuGet Status

A .NET client for adb, the Android Debug Bridge (SharpAdbClient)

SharpAdbClient is a .NET library that allows .NET applications to communicate with Android devices. It provides a .NET implementation of the adb protocol, giving more flexibility to the developer than launching an adb.exe process and parsing the console output.

Installation

To install SharpAdbClient install the SharpAdbClient NuGetPackage. If you're using Visual Studio, you can run the following command in the Package Manager Console:

PM> Install-Package SharpAdbClient

Getting Started

All of the adb functionality is exposed through the SharpAdbClient.AdbClient class. You can create your own instance of that class, or just use the instance we provide for you at SharpAdbClient.AdbClient.Instance.

This class provides various methods that allow you to interact with Android devices.

Starting the adb server

SharpAdbClient does not communicate directly with your Android devices, but uses the adb.exe server process as an intermediate. Before you can connect to your Android device, you must first start the adb.exe server.

You can do so by either running adb.exe yourself (it comes as a part of the ADK, the Android Development Kit), or you can use the AdbServer.StartServer method like this:

AdbServer server = new AdbServer();
var result = server.StartServer(@"C:\Program Files (x86)\android-sdk\platform-tools\adb.exe", restartServerIfNewer: false);

List all Android devices currently connected

To list all Android devices that are connected to your PC, you can use the following code:

var devices = AdbClient.Instance.GetDevices();

foreach(var device in devices)
{
    Console.WriteLine(device.Name);
}

Subscribe for events when devices connect/disconnect

To receive notifications when devices connect to or disconnect from your PC, you can use the DeviceMonitor class:

void Test()
{
    var monitor = new DeviceMonitor(new AdbSocket(new IPEndPoint(IPAddress.Loopback, AdbClient.AdbServerPort)));
    monitor.DeviceConnected += this.OnDeviceConnected;
    monitor.Start();
}

void OnDeviceConnected(object sender, DeviceDataEventArgs e)
{
    Console.WriteLine($"The device {e.Device.Name} has connected to this PC");
}

Manage applications

To install or uninstall applications, you can use the PackageManager class:

void InstallApplication()
{
    var device = AdbClient.Instance.GetDevices().First();
    PackageManager manager = new PackageManager(device);
    manager.InstallPackage(@"C:\Users\me\Documents\mypackage.apk", reinstall: false);
}

Send or receive files

To send files to or receive files from your Android device, you can use the SyncService class. When uploading a file, you need to specify the permissions of the file. These are standard Unix file permissions. For example, 444 will give everyone read permissions and 666 will give everyone write permissions. You also need to specify the date at which the file was last modified. A good default there is DateTime.Now.

void DownloadFile()
{
    var device = AdbClient.Instance.GetDevices().First();
    
    using (SyncService service = new SyncService(new AdbSocket(new IPEndPoint(IPAddress.Loopback, AdbClient.AdbServerPort)), device))
    using (Stream stream = File.OpenWrite(@"C:\MyFile.txt"))
    {
        service.Pull("/data/local/tmp/MyFile.txt", stream, null, CancellationToken.None);
    }
}

void UploadFile()
{
    var device = AdbClient.Instance.GetDevices().First();
    
    using (SyncService service = new SyncService(new AdbSocket(new IPEndPoint(IPAddress.Loopback, AdbClient.AdbServerPort)), device))
    using (Stream stream = File.OpenRead(@"C:\MyFile.txt"))
    {
        service.Push(stream, "/data/local/tmp/MyFile.txt", 444, DateTime.Now, null, CancellationToken.None);
    }
}

Run shell commands

To run shell commands on an Android device, you can use the AdbClient.Instance.ExecuteRemoteCommand method.

You need to pass a DeviceData object which specifies the device on which you want to run your command. You can get a DeviceData object by calling AdbClient.Instance.GetDevices(), which will run one DeviceData object for each device Android connected to your PC.

You'll also need to pass an IOutputReceiver object. Output receivers are classes that receive and parse the data the device sends back. In this example, we'll use the standard ConsoleOutputReceiver, which reads all console output and allows you to retrieve it as a single string. You can also use other output receivers or create your own.

void EchoTest()
{
    var device = AdbClient.Instance.GetDevices().First();
    var receiver = new ConsoleOutputReceiver();

    AdbClient.Instance.ExecuteRemoteCommand("echo Hello, World", device, receiver);

    Console.WriteLine("The device responded:");
    Console.WriteLine(receiver.ToString());
}

Consulting, Training and Support

This repository is maintained by Quamotion. Quamotion develops test software for iOS and Android applications, based on the WebDriver protocol.

In certain cases, Quamotion also offers professional services - such as consulting, training and support - related to SharpAdbClient. Contact us at [email protected] for more information.

History

SharpAdbClient is a fork of madb; which in itself is a .NET port of the ddmlib Java Library. Credits for porting this library go to Ryan Conrad.

madb's People

Contributors

bartsaintgermain avatar camalot avatar dgadelha avatar magic73 avatar pbielinski avatar qmfrederik avatar timosalomaki avatar xixixixixiao avatar youngjaekim 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  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

madb's Issues

This is not the official source of MADB

You should state that this is a fork. The name madb is the name of the official project. There are official nuget packages, but you have created your own. While you did provide myself as an author, again, it is using the madb, which is the name of the official project, but not the ID on nuget.

As it stands, you are violating the license:

  1. Trademarks.
    This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.

Please make it known that is is a fork of the original project and change the name of the nuget package id.

Device State always showing Offline

Hi,

I have SharpADB working and I get the Device Connected event when I cradle mu device. However the eventargs aare only populated with the Device Serial and the STATE shows Offline.

Can you think of any reason the device would be OFFLINE, even though I get the events and can read the serial number in the eventargs?

Thanks Much!

Delete file

Are you using this code to delete the file?
this.Device.ExecuteShellCommand("rm " + remoteFilePath, null);

No direct call to delete the method?
for example

 foreach (var file in service.GetDirectoryListing(directory))
                    {
                        //file.Delete();
                    }

Could not get IMEI no. of Connected Device.

I am creating a WPF c# application for mobile diagnostics and I m using SharpADB client. I m getting device details but not IMEI and I want it to show it in for desktop app. Is there any technique for getting IMEI and current Battery Level via SharpADB.
Ps: If someone knows about any other library for getting these data. Please Suggest it. Thanks in advance.

CreateFromAdbData throws ArgumentException

When one of AdbClient.Instance.GetDevices() value has
'99000000 device product:iz_x200i model:NX_X100TT device:iz_x200i transport_id:1'

CreateFromAdbData(...) regex rule throws exception as below.

   at: SharpAdbClient.DeviceData.CreateFromAdbData(String data)
   at: SharpAdbClient.AdbClient.<>c.<GetDevices>b__23_0(String d)
   at: System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
   at: System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at: System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at: SharpAdbClient.AdbClient.GetDevices()

InstallPackage does not work

InstallPackage tries to copy apk file to temporary directory on device and then install it. It gets this constant, but this path does not exist (at least at my emulator) and InstallPackage fails.

public const string TempInstallationDirectory = "/storage/sdcard0/tmp/";

For my case I changed it to /local/data/tmp and install started to work.

How can i use the class FileSystem

Hello,

The class FileSystem inside the module extensions does not seem to be available on nuget package.

I would like to use it to delete some files on device.

How can I achieve that?

Thanks

uiautomator runtest:Unsupported standalone parameter

 void test()
        {
            var device = AdbClient.Instance.GetDevices().First();
            var receiver = new ConsoleOutputReceiver();

            AdbClient.Instance.ExecuteRemoteCommand("uiautomator runtest demo.jar - c com.siterui.demo.Test", device, receiver);
            // receiver.ToString()
            //responded: Unsupported standalone parameter
        }

The phone did not execute the test code
responded:
Unsupported standalone parameter

Cmd.exe running code:

adb shell uiautomator runtest demo.jar -c com.siterui.demo.Test

Correctly execute the test code.

responded:

Microsoft Windows [版本 10.0.10240]
(c) 2015 Microsoft Corporation. All rights reserved.

C:\Users\Administrator>adb shell uiautomator runtest demo.jar -c com.siterui.demo.Test
INSTRUMENTATION_STATUS: numtests=1
INSTRUMENTATION_STATUS: stream=
com.siterui.demo.Test:
INSTRUMENTATION_STATUS: id=UiAutomatorTestRunner
INSTRUMENTATION_STATUS: test=testDemo
INSTRUMENTATION_STATUS: class=com.siterui.demo.Test
INSTRUMENTATION_STATUS: current=1
INSTRUMENTATION_STATUS_CODE: 1
INSTRUMENTATION_STATUS: numtests=1
INSTRUMENTATION_STATUS: stream=.
INSTRUMENTATION_STATUS: id=UiAutomatorTestRunner
INSTRUMENTATION_STATUS: test=testDemo
INSTRUMENTATION_STATUS: class=com.siterui.demo.Test
INSTRUMENTATION_STATUS: current=1
INSTRUMENTATION_STATUS_CODE: 0
INSTRUMENTATION_STATUS: stream=
Test results for WatcherResultPrinter=.
Time: 0.79

OK (1 test)


INSTRUMENTATION_STATUS_CODE: -1

C:\Users\Administrator>

java code:

package com.siterui.demo;

import com.android.uiautomator.core.UiDevice;
import com.android.uiautomator.testrunner.UiAutomatorTestCase;

public class Test extends UiAutomatorTestCase {

    public void testDemo(){
        UiDevice.getInstance().pressHome();
    }

}

AdbSocket closing connection

Hello, I have a question about the AdbSocket.

I want to capture the emulator screen, so I'm using AdbSocket to get a faster response than sending adb commands using the shell or using the GetFrameBuffer().

But, since I have to keep sending the same command to the emulator for a few minutes I tried to use AdbSocket to keep a connection 'live' and send/receive the data faster (I guess it would be faster, I couldn't try yet), so I'm kinda using this:

IAdbSocket socket = Factories.AdbSocketFactory(AdbClient.Instance.EndPoint);
AdbClient.Instance.SetDevice(socket, AndroidDevice);

var command = "screencap -p /sdcard/Pictures/test.png";

socket.SendAdbRequest($"shell:{command}");
var response = socket.ReadAdbResponse();
var stream = new StreamReader(socket.GetShellStream()).ReadToEnd();

I'm reading the socket stream just to make sure the image was generated, if I don't do this the image might not be generated for some reason.

Anyway, the problem is that after that the socket.Connected becomes "false", so I can not use the same socket connection to send the same command again, so I have to execute the code above again, which I guess increases its delay to execute and generate the image for me.

There is a way to "fix" it? Or there is a best way to get the Android emulator screen content faster? (It doesn't necessarilly need to generate the .png file since I'm using it just to create a C# Bitmap object and read its pixels.)

Thank you

DeviceMonitor failure

Hi,

I have been using SharpAdbClient with great pleasure. However, recently I notice that occasionally DeviceMonitor would throw an exception and failed to detect new adb devices

07:34 E/AdbSocket: Got reply 'FAIL', diag='device offline'
Exception thrown: 'SharpAdbClient.Exceptions.AdbException' in SharpAdbClient.dll
Exception thrown: 'SharpAdbClient.Exceptions.AdbException' in SharpAdbClient.dll
Exception thrown: 'System.AggregateException' in mscorlib.dll
Exception thrown: 'SharpAdbClient.Exceptions.AdbException' in SharpAdbClient.dll
Exception thrown: 'SharpAdbClient.Exceptions.AdbException' in SharpAdbClient.dll

When this happens, I can see the device via adb command line. I guess I can try to catch this exception and restart the monitor, but thought it might be better to understand what has caused the problem.

My code is simply below.

var result = AdbServer.Instance.StartServer(@"adb.exe", true);
adbMonitor = new DeviceMonitor(new AdbSocket(AdbServer.Instance.EndPoint));
adbMonitor.DeviceConnected += this.OnDeviceConnected;
adbMonitor.DeviceDisconnected += this.OnDeviceDisconnected;
adbMonitor.Start();

Did I do anything wrong?

Many thanks.

Ning

OnDeviceConnected serial when fastboot command issues against 1st device

I'm writing an WPF application using C# and .NET on a Windows 10 computer. The application is supposed to allow multiple Android devices to be plugged in via USB, then install OS version 4.2.2 and various apps. Initially, the devices were to arrive with OS already installed. My program worked well in an asynchronous fashion.

However, once I had to install the operating system, I needed to boot into fastboot mode (i.e. adb -s [serial-number-here] reboot bootloader). Unfortunately, the OnDeviceConnected() method/event does not fire until the OS is installed and booted back into ADB mode (i.e. fastboot -s [serial-number-here] reboot). The next device in the queue is unfortunately locked by that time, so no further progress can be made, just timeouts from then on.

So, is there a way to allow the Connected and Disconnected events fire asynchronously even if a particular device is booted into fastboot mode?

Package Manager broken with Android O beta

With O it appears there is a base64 checksum in the directory of third party packages.

package:/data/app/com.google.android.apps.plus-qQaDuXCpNqJuQSbIS6OxGA==/base.apk=com.google.android.apps.plus

The additional = breaks the check in PackageManagerReceiver on line.Split(':', '=')

[Feature Request] Fastboot

It's nice that this library has a good support for most ADB functions, but do you have any plans to implement the Fastboot features too?

Thanks.

GetDevices doesn't work with SDK Platform Tools 27.0.1

Hello there,

I am using SharpAdbClient 2.1.0, and when using the command GetDevices, I get the following error:

Invalid device list data '00bc13bcf4bacc62 device product:bullhead model:Nexus_5X device:bullhead transport_id:1'

This occurs when using Android SDK Platform- Tools 27.0.1 (as of December 2017, the latest version of Platform Tools).

When I set the environment variable to use an earlier version of adb.exe, this function works.

The command adb devices returns the following:

List of devices attached 00bc13bcf4bacc62 device

So it looks like the phone, a Nexus 5x with Android 8.1, is connected and identified. I can also use other apps and commands to communicate with the phone. I've had the same results with a Moto G5 Plus running 7.0, and a Nexus 6 running 7.0 as well.

Has anyone experiences incompatibilities with Platform Tools 27.0.1 and SharpAdbClient 2.1.0?

InstallPackage does not work on Android 7

Hello, today faced with a problem. Installing applications does not work on Android 7.
I got an incomprehensible error "An unknown error occurred."
Until I thought of what to do ((

AdbClient add CreateReverse

Can you add CreateReverse to AdbClient?

public int CreateReverse(DeviceData device, string local, string remote)

Change Request: Encoding setable by api user

Hello, i have a change request, if possible make the Encoding setable. Reason for this is:

If you use the follwing comand to dump the ui hierachy to stdout, then e,g, cyrellic characters are broken, because the uiautomator dump is utf8 and the default encoder is ansi8859.

AdbClient.Instance.ExecuteRemoteCommand($"uiautomator dump /dev/tty", _device, _receiver);

Class: AdbClient

        /// <summary>
        /// Gets the encoding used when communicating with adb.
        /// </summary>
        public static Encoding Encoding
        { get; } = Encoding.GetEncoding(DefaultEncoding);

PULL service for cyrillic

Hello

I have a problem with PULL command in SyncService modul, when I want to download file from device with CYRILLIC name of folder in path.
As exemple /DCIM/Альбом/1234-1234.jpg

Commands that are sent with the background operator '&' of linux, are not executed

I am sending the following commands through the client:

  1. mkfifo /tmp/server-input
  2. tail -f /tmp/server-input | client_menu &
  3. echo 1 > /tmp/server-input &
    This should send the number 1 to the client that is running on the background (client_menu).
    When I run directly the same commands on the linux machine, they work perfectly. But sending them through the Adb Sharp Client they seem not to be executed and they do not show up on the process list.

RunLogServiceAsync Outputting Only a Single PID

Hello.

First of all thank you for this library it's saved me a great deal of time. However I am a bit stumped hopefully someone can help me out. I'd like to capture logcat activity that mimics adb logcat in a console. To do so I'm using code resembling the following:

Action<SharpAdbClient.Logs.LogEntry> messageCallback = (entry) =>
{
    AndroidLogEntry androidEntry = (AndroidLogEntry)entry;
    OutputLog(androidEntry.Id + " " + androidEntry.ProcessId + " " + androidEntry.Message);
};

AdbServer.Instance.StartServer(adbPath, false);
DeviceData firstDevice = AdbClient.Instance.GetDevices().First();
AdbClient.Instance.RunLogServiceAsync(firstDevice, messageCallback, CancellationToken.None);

This works fine besides for the fact that on all of my test devices the returned logs all represent single PID with ~100 entries then the active socket is disposed. I've tried multiple combinations of LogId configurations with the same result. In all cases using Android's monitor tool to easily confirm, I've determined that I'm only receiving log entries from the AlarmManager process.

Does anyone know if this is an issue with how I'm using the library or a possible issue with the library itself? Any info here is most welcome.

Thanks for the help!

Devicemonitor.Start() hangs

Hi
If a android device is already connnected and you start monitoring:

var result = server.StartServer(p, restartServerIfNewer: false);      
      var monitor = new DeviceMonitor(new AdbSocket(new IPEndPoint(IPAddress.Loopback, AdbClient.AdbServerPort)));
      monitor.DeviceConnected += Monitor_DeviceConnected;
      monitor.DeviceDisconnected += Monitor_DeviceDisconnected;
      monitor.Start();

monitor.Start(); is hanging forever.

Method call callback/delegate

Hi, first off thanks for this library. It been quite helpful for me. Is there a way to get a callback when you call
AdbClient.Instance.Install(device, fs);
Something to show that the above method call is working so user can wait and then delegate/callback to show success or failure.

List of properties empty for devices where `/sbin/getprop` does not work, but `/system/bin/getprop` does

The device is a Sony Ericsson Xperia running Android 4.2.2, with CyanogenMod version 10.1-20150301-UNOFFICIAL-es209ra

In this scenario, Device.Properties returns an empty list.

Consider the following output:

C:\Users\FrederikCarlier>adb devices
List of devices attached
0123456789ABCDEF        device

C:\Users\FrederikCarlier>adb shell getprop
getprop: applet not found

C:\Users\FrederikCarlier>adb shell /sbin/getprop
getprop: applet not found

C:\Users\FrederikCarlier>adb shell /system/bin/getprop
[dalvik.vm.checkjni]: [false]
[dalvik.vm.dexopt-data-only]: [1]
(...)

The properties can be retrieved, but only if /system/bin/getprop is called.

Any C# samples to get me started

I am very interested in using this class but am having a heck of a time in C#.

I have added SharpAdbClient to my project using NuGet package manager.

For instance - I would like to setup Device Monitoring and have implemented the following in my Form Load event:
AdbServer.Instance.StartServer(@"C:\adb.exe", true);
DeviceMonitor adbMonitor = new DeviceMonitor(new AdbSocket(AdbServer.Instance.EndPoint));
adbMonitor.DeviceConnected += this.OnDeviceConnected;
adbMonitor.DeviceDisconnected += this.OnDeviceDisconnected;
adbMonitor.Start();

I get an error when initializing the new DeviceMonitor telling me that AdbServer does not contain a definition for EndPoint - yet this code is your example.

Any assistance or a small sample C# app to get me started would be greatly appreciated.

Trouble connecting to ADB server on OS X

Hi there!

I'm currently looking into porting my codebase (C# .NET Framework 4.5.2 with VS2015) to OS X (and further Linux) and I'm running into an issue while connecting to the ADB server using AdbClient.Instance.Connect(hostname); where hostname is a local network IP á la 192.168.0.x.

The error returned is

[ERROR] FATAL UNHANDLED EXCEPTION: System.Net.Sockets.SocketException: Connection refused
  at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP) <0x86a98c0 + 0x00167> in <filename unknown>:0 
  at SharpAdbClient.TcpSocket.Connect (System.Net.EndPoint endPoint) <0x86a9868 + 0x0001f> in <filename unknown>:0 
  at SharpAdbClient.AdbSocket..ctor (System.Net.EndPoint endPoint) <0x86a75c8 + 0x0007c> in <filename unknown>:0 
  at SharpAdbClient.Factories+<>c.<Reset>b__17_0 (System.Net.EndPoint endPoint) <0x86a7580 + 0x0002f> in <filename unknown>:0 
  at SharpAdbClient.AdbClient.Connect (System.Net.DnsEndPoint endpoint) <0x86b4570 + 0x00039> in <filename unknown>:0 
  at SharpAdbClient.AdbClientExtensions.Connect (IAdbClient client, System.String host) <0x86b4390 + 0x00076> in <filename unknown>:0 
  at CoCB.Utils.AdbHelper.ConnectToHost (System.String hostname) <0x86b4330 + 0x0001b> in <filename unknown>:0 
  at CoCB.Utils.AdbHelper.Connect () <0x86b4298 + 0x0006b> in <filename unknown>:0 
  at CoCB.Program.Main () <0x6bdf38 + 0x0012b> in <filename unknown>:0 

The same code is confirmed to work on Windows 10. I can see that under Unix based operating systems, you take a different approach to connecting to the ADB server, which connects to a socket at "/tmp/5037". I'm not very proficient with *nix sockets, so I don't know if I'm doing something wrong here. I can't find the requested socket file in the file system (through Finder or ls).

The server is started through AdbServer.StartServer("/Users/xxx/Library/Android/sdk/platform-tools/adb", true); and returns code 'Started' so I'm assuming the server was started successfully. But somehow the connection still fails. If I try to open a connection with

var socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

socket.Connect ("192.168.0.106", 5555);

the connection opens just fine (socket.Connected is True).

Would you have any idea where I could start with this?

Cheers
Philipp

EDIT

Replacing TcpSocket.cs

//this.socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

and AdbServer.cs

//EndPoint = new UnixEndPoint($"/tmp/{AdbServerPort}");
EndPoint = new IPEndPoint(IPAddress.Loopback, AdbServerPort);

seems to connect to the device. I can query the DeviceData class, but I haven't tried sending any commands yet. Is there any specific reason you are using Mono.Posix specific endpoints for OS X and Linux?

Is there a way to run backup commands?

Basically I was hoping to be able to do the equivalent to

adb.exe backup <filename> --twrp system cache data boot --compress

but I can't seem to find one. Which is fine, I can directly call the executable if I need too, but I was hoping for something baked in. Regardless of the answer, I appreciate the work that has gone into this project and I hope you are having a great day/night!

New feature request: Create port reverse

Right now it is possible to create a port forward by calling the AdbClient CreateForward method.
Can you please implement the complementary CreateReverse method?

Slow executions

Hello.

I'm testing this lib, but I'm having some issues with high delay to execute some actions, for example, doing a simple:

AdbClient.Instance.ExecuteRemoteCommand("adb shell input tab 100 500", device, receiver);

It takes like 3~4 seconds to be executed, is that correct or am I missing something?

adb root command

Hi. I think you need a command adb root
Which will restart adbd with admin rights.

Alternativ for GetFrameBuffer?

Hi,

i have to get a screenshot every 1/2sec. GetFrameBufferAsync work like a charm and took normaly 0.5s for proceed. But is use about 30% CPU-Use if i call it frequently.

Is there maybe an other way to get the Screencontent frequently?

Btw. it also looks ike there is a memory leak in this function because if i run it frequently over a longer time the RAM-Use also grows and grows :)

Greetings

Device Disconnect

With AdbClient.Instance.Connect I can connect to a device at a particular host address. How can I force the disconnect (e.g, adb disconnect ) via the AdbClient? I expected a Disconnect method to exist alongside the Connect method.

We are working with multiple connected devices and don't want to shutdown the device in order to disconnect from adb server.

Add support for screenrecord

One of the outcomes of #40 was that we may want to add support for screenrecord as a high-performance way of capturing the screen of an Android device.

Compile error in extensions

There is a compile error in method RunLogService in file Device.cs

    public IEnumerable<LogEntry> RunLogService(params LogId[] logNames)
    {
        return AdbClient.Instance.RunLogService(this.DeviceData, logNames);
    }

Error CS1061 'IAdbClient' does not contain a definition for 'RunLogService' and no extension method 'RunLogService' accepting a first argument of type 'IAdbClient' could be found (are you missing a using directive or an assembly reference?)

It seems that there is only RunLogServiceAsync.

I just commented it out since I don't need it within my project but it would be nice if I could use the project as it is on GitHub.

Also, Would it be possible if the extensions were included automatically in the SharpAdbClient nuget package that way you don't have to add the project to your solution.

Great work so far thank you for the amazing wrapper!!!

File upload failed

Minicap is a file, not a folder.
File no suffix, upload failed

Error prompt:
Failed to pull '/data/local/tmp/minicap'. No such file or directory

   public void pushFile(string localpath, string devicepath)
        {
        //localpath:Lib/minicap/bin/armeabi-v7a/minicap
        //devicepath:/data/local/tmp
            var filename = new FileInfo(localpath).Name;
            var remotepath = devicepath + @"/" + filename;
            using (ISyncService service = Factories.SyncServiceFactory(device))
            {
                var stat = service.Stat(remotpath);
                if (stat.Size == 0)
                {
                    using (Stream stream = File.OpenWrite(localpath))
                    {
                        service.Pull(remotepath, stream, null, CancellationToken.None);
                    }
                }
            }
        }

Problem with "v2.1.0-beta334"

I got the following error on update from nuget:

Failed to add reference. The package 'SharpAdbClient' tried to add a framework reference to 'System.Runtime' which was not found in the GAC. This is possibly a bug in the package. Please contact the package owners for assistance

Btw. as u can see here:

https://www.nuget.org/packages/sharpadbclient/2.1.0-beta334

It would likt to install System.Buffers (>= 4.3.0) on NETFramework 4.5 which is also included since 1.1 ;)

AdbClient.Instance.Install() fails if apk is already installed

When attempting to use AdbClient.Instance.Install() with an APK that is already installed on the target device, a SharpAdbClient.Exceptions.AdbException is received.

Possible solution:
Check if already installed, have a bool flag as function parameter to determine if it should be skipped or should be uninstalled/installed

Calling code:

foreach (FileInfo apkFile in new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, "Resources\\apk")).GetFiles("*.apk").ToList())
{
    Console.Write($"Installing Package:{apkFile.Name}");
    using (FileStream fs = new FileStream(apkFile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    {
        try
        {
            AdbClient.Instance.Install(device, fs);  // Exception thrown if already installed.
            Console.WriteLine("     Done.");
        }
        catch (SharpAdbClient.Exceptions.AdbException ex) { Console.WriteLine("     Failed" + ex.Message); }
    }
}

Exception data:

SharpAdbClient.Exceptions.AdbException
HResult=0x80131500
Message=Failure [INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install com.adobe.reader without first uninstalling.]
Source=SharpAdbClient
StackTrace:
at SharpAdbClient.AdbClient.Install(DeviceData device, Stream apk, String[] arguments)
at TabletPrep.Program.Main(String[] args) in \source\repos\ConsoleApp1\ConsoleApp1\Program.cs:line 102

readme in the root is wrong

Especially the ability to push files.
using (SyncService service = new SyncService(new AdbSocket(), device)) //new AdbSocket() is wrong
using (Stream stream = File.OpenRead(@"C:\MyFile.txt"))
{
service.Push(stream, "/data/MyFile.txt", null, CancellationToken.None); //params is wrong
}

Exception with latest version of Java while using ExecuteRemoteCommand()

I recently updated to the latest version of Java .i.e. Version 8 Update 121

When I execute any command on my sqlite3 database in my android app, this exception comes along with the expected result:
Code
AdbClient.Instance.ExecuteRemoteCommand("sqlite3 /data/data/com.TestApp/databases/msgstore.db \"select _name, _id from joiners order by _id desc limit 1\"", device, receiver);

Exception
Error: Unknown option: -
java.lang.NullPointerException
at com.android.commands.am.Am.runStart(Am.java:807)
at com.android.commands.am.Am.onRun(Am.java:285)
at com.android.internal.os.BaseCommand.run(BaseCommand.java:47)
at com.android.commands.am.Am.main(Am.java:91)
at com.android.internal.os.RuntimeInit.nativeFinishInit(Native Method)
at com.android.internal.os.RuntimeInit.main(RuntimeInit.java:258)
at dalvik.system.NativeStart.main(Native Method)
Saurabh Sharma|29

The last line contains the expected result.

SharpAdbClient push

public void Push(Stream stream, string remotePath, int permissions, DateTime timestamp, IProgress progress, CancellationToken cancellationToken);

permissions 该怎么赋值

Monitor Exception - Reconnect

Hi, I'm using the latest version of the library, with a Samsung Galaxy S8+, ADB 1.0.40

You have to add a new state value in the RegExp expression, inside DeviceData.
"connecting"

when I connect my s8 to PC, I got two messages (connecting and device), and your MonitorLibrary throw an exception sinche it fails to match the regexp for the first message.

Probably the new ADB changes how it handles the connections.

I downloaded the source code, added the "connecting" string to the regexp, and now it works.
But now, on connection, there are two events fired:

  • connecting message, fire the OnDeviceConnected
  • device message: fire the OnDeviceChanged

I just pulled a request for this fix :)

How to stop ExecuteRemoteCommand

I'm writing uiautomator test program. I'm can start shell with ExecuteRemoteCommand but i don't know how to stop it. (In cmd is Ctrl+C). Can't Anyone Help Me? Thanks.

GetFrameBuffer CPU-Use

Hi,

it looks like there is a CPU-Use issue in this function.

But i think a sample is even more helpfull to reproduce:

var device = AdbClient.Instance.GetDevices().First();

while (true)
{
    var img = AdbClient.Instance.GetFrameBufferAsync(device, CancellationToken.None).Result;
    Thread.Sleep(100);
}

The CPU-Use from adb.exe is only 0-2%. But the GetFrameBufferAsync-function jumps to 30% (if VS dont lie). Donno what happend here :/

(i know it's a bit like #39 but i truly think the CPU-Use problem is not an adb-problem)

Greetings

EDIT

i think i found the problem. The AdbSocket.Read use a while loop which some times runs in idle and let the CPU-Use grow. A simple Thread.Sleep(1); reduce the CPU-Use down to < 10%. A Thread.Sleep(10); to < 5%.

Maybe there is a more efficient way to check for idle. But i'm relative sure that this is the problem.

Before:

before
(Sry for the german image)

After (1ms delay):

after_1ms
(Sry for the german image)

EDIT2

Btw. GetFrameBufferAsync could also use AdbSocket.ReadAsync instand of the sync version. But the AdbSocket.ReadAsync is also missing the Thread.Sleep(1); or somthing more efficient^^

EDIT3

It does not even make a big different in result (run time of the function) if use Sleep(1) or Sleep(10). But CPU-Use also drops again 50%. So for me 10ms would be perfect.

But it would be perfect if the socked it self would block until there are no data to Receive.

EDIT4

Btw. an optimum would be if madb could deliver a stream of this:

http://stackoverflow.com/questions/26786926/android-screen-capture

I try it in ABD and its very very very fast.

Could not load file or assembly 'Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756'

Hi,
When I got devices with the following code:

try
{
var devices = AdbClient.Instance.GetDevices();
foreach (var device in devices)
{
Console.WriteLine(device.Name);
}
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}

It throwing an exception likes this:
Exception thrown: 'System.TypeInitializationException' in SharpAdbClient.dll
at SharpAdbClient.AdbServer.get_Instance() location C:\projects\madb\SharpAdbClient\AdbServer.cs:line 113
at Dot42.AdbLib.DeviceMonitor.Run() location E:\WorkRelated\Projects\UTester-windows\UTestor\AdbLib\DeviceMonitor.cs:line 161
Step into: Stepping over property 'SharpAdbClient.AdbServer.get_Instance'. To step into properties, go to Tools->Options->Debugging and uncheck 'Step over properties and operators (Managed only)'.
Exception thrown: 'System.TypeInitializationException' in SharpAdbClient.dll
Step into: Stepping over property 'System.Console.get_Out'. To step into properties, go to Tools->Options->Debugging and uncheck 'Step over properties and operators (Managed only)'.
at SharpAdbClient.AdbServer.get_Instance() location C:\projects\madb\SharpAdbClient\AdbServer.cs:line 113
at Dot42.AdbLib.DeviceMonitor.Run() location E:\WorkRelated\Projects\UTester-windows\UTestor\AdbLib\DeviceMonitor.cs:line 161

How to solve this problem? Thanks!

INSTALL_FAILED_INVALID_APK

I apologize for the lack of information, but I'm attempting to install a package that's on my desktop to the android simulator. This is half of the stack trace from the PackageInstallationException. Any thoughts?

at SharpAdbClient.DeviceCommands.PackageManager.InstallRemotePackage(String remoteFilePath, Boolean reinstall) in C:\projects\madb\SharpAdbClient\DeviceCommands\PackageManager.cs:line 137
at SharpAdbClient.DeviceCommands.PackageManager.InstallPackage(String packageFilePath, Boolean reinstall) in C:\projects\madb\SharpAdbClient\DeviceCommands\PackageManager.cs:line 116

Memory leak in RefreshAsync while using a CancellationToken?

Hi,

it is me or is RefreshAsync creates a memory leak if using with a CancellationToken? If i use it like the sample (CancellationToken.None) it workes like a charm. But if i pass through the CancellationToken into the function the memory use increase (faster on fast responed devices like Emulators(Nox,Bluestacks) and slowly on normal devices). My Test-Function:

static void Main(string[] args)
{
    var ct = new CancellationTokenSource();
    TestCancellationToken(ct.Token);
    Console.ReadKey();
}

private static async void TestCancellationToken(CancellationToken ct)
{
    var device = AdbClient.Instance.GetDevices().First();

    var framebuffer = AdbClient.Instance.CreateRefreshableFramebuffer(device);

    while (!ct.IsCancellationRequested)
        await framebuffer.RefreshAsync(ct).ConfigureAwait(false);
}

adb:notfound

use abd with nox but abd:notfound when execute command

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.