/// <summary>
        /// Execute adb command to selected device
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        internal string Execute(string command, [CallerLineNumber] int lineNumber = 0, [CallerMemberName] string caller = null)
        {
            if (selectedDevice == null)
            {
                if (string.IsNullOrEmpty(adbipport))
                {
                    Console.Error.WriteLine("No adbipport registered. Please check you called SelectDevice(string adbipsocket)");
                    return(string.Empty);
                }
                if (!SelectDevice(adbipport))
                {
                    Console.Error.WriteLine("No such device found");
                    return(string.Empty);
                }
            }
            ConsoleOutputReceiver receiver = new ConsoleOutputReceiver();

            try
            {
                client.ExecuteRemoteCommand(command, selectedDevice, receiver);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("device offline"))
                {
                    throw new Exception("device offline");
                }
                receiver.AddOutput(ex.ToString());
            }
            logger.WritePrivateLog("Execute " + command + " Result:" + receiver.ToString(), lineNumber, caller);
            return(receiver.ToString());
        }
示例#2
0
        public void ConnectPhone(string Serial)
        {
            StartServer();

            var dns = GetCacheDnsEndPoint(Serial);

            if (dns != null)
            {
                AdbClient.Connect(dns.Host);
                DevicesConnected.Add(Serial, dns);
                return;
            }

            var deviceData = AdbClient.GetDevices().First(x => x.Serial == Serial);

            // Get ip addresse of the device
            var receiver = new ConsoleOutputReceiver();

            AdbClient.ExecuteRemoteCommand("ip addr show wlan0", deviceData, receiver);
            var ip = receiver.ToString().Split('\n').Where(x => x.Contains("inet")).First()
                     .Trim().Split(' ')[1].Split('/').First();

            // Setup the tcpip
            port++;
            CommandADB.StartTcpip(Serial, port);

            AdbClient.Connect(ip);
            dns = new DnsEndPoint(ip, port);
            DevicesConnected.Add(Serial, dns);
            DeviceCache.Add(Serial, dns);
        }
示例#3
0
        private void Button7_Click(object sender, EventArgs e)
        {
            var receiver = new ConsoleOutputReceiver();

            AdbClient.Instance.ExecuteRemoteCommand("settings put system user_rotation 2", Device, receiver);
            MessageBox.Show(Device.Name + " says:\n \n" + receiver.ToString());
        }
示例#4
0
        public string SendCommand(string command)
        {
            var receiver = new ConsoleOutputReceiver();

            AdbClient.Instance.ExecuteRemoteCommand(command, Data, receiver);
            return(receiver.ToString().Trim());
        }
示例#5
0
        private void Button8_Click(object sender, EventArgs e)
        {
            var receiver = new ConsoleOutputReceiver();

            AdbClient.Instance.ExecuteRemoteCommand("settings put secure location_providers_allowed ' '", Device, receiver);
            MessageBox.Show(Device.Name + " says:\n \n" + receiver.ToString());
        }
示例#6
0
        private void Button1_Click(object sender, EventArgs e)
        {
            var receiver = new ConsoleOutputReceiver();

            AdbClient.Instance.ExecuteRemoteCommand("dumpsys battery set level " + numericUpDown1.Value, Device, receiver);
            MessageBox.Show(Device.Name + " says:\n \n" + receiver.ToString());
        }
示例#7
0
        private void Button1_Click(object sender, EventArgs e)
        {
            var receiver = new ConsoleOutputReceiver();

            AdbClient.Instance.ExecuteRemoteCommand("am start -a android.intent.action.CALL -d tel:" + textBox1.Text, Device, receiver);
            MessageBox.Show(Device.Name + " says:\n \n" + receiver.ToString());
        }
示例#8
0
        public bool CheckFocusedApp()
        {
            string command  = $"dumpsys window windows | grep -E 'mCurrentFocus'";
            var    receiver = new ConsoleOutputReceiver();

            try
            {
                AdbClient.Instance.ExecuteRemoteCommand(command, Device, receiver);
            }
            catch
            {
                Compiler.ExceptionListener.ThrowSilent(new ExceptionHandler(ExceptionType.DriverException,
                                                                            $"Focus check timed out. Please check your device connection."), true);
                return(false);
            }
            var echo = receiver.ToString();

            if (echo.Contains(AppPackage))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
示例#9
0
        private void Button2_Click(object sender, EventArgs e)
        {
            var receiver = new ConsoleOutputReceiver();

            AdbClient.Instance.ExecuteRemoteCommand("input keyevent 6", Device, receiver);
            MessageBox.Show(Device.Name + " says:\n \n" + receiver.ToString());
        }
示例#10
0
        /// <summary>
        /// Run command with ADB on device
        /// </summary>
        /// <param name="device">The device data object.</param>
        /// <param name="command">Command to be run.</param>
        /// <returns></returns>
        private static String RunCommand(DeviceData device, String command)
        {
            var receiver = new ConsoleOutputReceiver();

            AdbClient.Instance.ExecuteRemoteCommand(command, device, receiver);
            return(receiver.ToString());
        }
示例#11
0
        private string resultCommand(string Command)
        {
            var receiver = new ConsoleOutputReceiver();

            AdbClient.Instance.ExecuteRemoteCommand(Command, CurrentDevice, receiver);
            return(receiver.ToString());
        }
示例#12
0
        public string SendShellCommand(string c)
        {
            var receiver = new ConsoleOutputReceiver();

            AdbClient.Instance.ExecuteRemoteCommand(c, Device, receiver);
            return(receiver.ToString());
        }
示例#13
0
        private void Button3_Click(object sender, EventArgs e)
        {
            var receiver = new ConsoleOutputReceiver();

            AdbClient.Instance.ExecuteRemoteCommand(string.Format("wm size {0}x{1}", numericUpDown2.Value, numericUpDown3.Value), Device, receiver);
            MessageBox.Show(Device.Name + " says:\n \n" + receiver.ToString());
        }
示例#14
0
        public void ShellCommand(string command)
        {
            if (data != null)
            {
                var receiver = new ConsoleOutputReceiver();

                AdbClient.Instance.ExecuteRemoteCommand(command, data, receiver);
                //AppendText(richTextBox1, "ADB Log : Execute Command " + command + "/n", Color.Gold);
                if (!receiver.ToString().Equals(""))
                {
                    //AppendText(richTextBox1, "ADB Log : Error Command " + receiver.ToString(), Color.Gold);
                }

                Console.WriteLine("The device responded:");
                Console.WriteLine(receiver.ToString());
            }
        }
示例#15
0
文件: Program.cs 项目: sp0x/madb.core
        private static void EchoTest(string serial)
        {
            var device   = GetDevice(serial);
            var receiver = new ConsoleOutputReceiver();

            AdbClient.Instance.ExecuteRemoteCommand("echo Hello, World", device, receiver);
            Console.WriteLine("The device responded:");
            Console.WriteLine(receiver.ToString());
        }
示例#16
0
文件: Program.cs 项目: sp0x/madb.core
        public static void ListDir(string serial, string basePath)
        {
            var inst     = AdbClient.Instance;
            var dev      = GetDevice(serial);
            var receiver = new ConsoleOutputReceiver();

            inst.ExecuteRemoteCommand($"ls {basePath}", dev, receiver);
            Console.WriteLine(receiver.ToString());
        }
示例#17
0
        private void TouchScreenListener_MouseClick(object sender, MouseEventArgs e)
        {
            int x        = Cursor.Position.X - Location.X;
            int y        = Cursor.Position.Y - Location.Y;
            var receiver = new ConsoleOutputReceiver();

            AdbClient.Instance.ExecuteRemoteCommand(string.Format("input tap {0} {1}", x * 2, y * 2), Device, receiver);
            Console.WriteLine(Device.Name + " says:\n \n" + receiver.ToString());
        }
示例#18
0
        public string Argumentos(String argumento)
        {
                var device = AdbClient.Instance.GetDevices().First();
                var receiver = new ConsoleOutputReceiver();

                AdbClient.Instance.ExecuteRemoteCommand(argumento, device, receiver);

                return receiver.ToString();
        }
示例#19
0
        void EchoTest(string s, string command)
        {
            var device = GetByName(s);

            if (device != null)
            {
                var receiver = new ConsoleOutputReceiver();

                AdbClient.Instance.ExecuteRemoteCommand(command, device, receiver);
                AppendText(richTextBox1, "ADB Log : Execute Command " + command + "/n", Color.Gold);
                if (!receiver.ToString().Equals(""))
                {
                    AppendText(richTextBox1, "ADB Log : Error Command " + receiver.ToString(), Color.Gold);
                }

                Console.WriteLine("The device responded:");
                Console.WriteLine(receiver.ToString());
            }
        }
示例#20
0
        private void Form1_Load(object sender, EventArgs e)
        {
            AdbServer server = new AdbServer();
            var       result = server.StartServer(@"C:\Users\i.g.dincu\Downloads\platform-tools_r30.0.4-windows\platform-tools\adb.exe", restartServerIfNewer: false);

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

            AdbClient.Instance.ExecuteRemoteCommand("ip route", device, receiver);

            MessageBox.Show(receiver.ToString());
        }
示例#21
0
文件: Form1.cs 项目: adryzz/AdbCsGui
        private void button3_Click(object sender, EventArgs e)
        {
            var          device       = AdbClient.Instance.GetDevices().First();
            var          receiver     = new ConsoleOutputReceiver();
            DialogResult dialogResult = MessageBox.Show("Be sure to execute only trusted commands. Run?", "Shell", MessageBoxButtons.YesNo);

            if (dialogResult == DialogResult.Yes)
            {
                AdbClient.Instance.ExecuteRemoteCommand(textBox1.Text, device, receiver);
                MessageBox.Show(device.Name + " says:\n \n" + receiver.ToString());
            }
        }
示例#22
0
        public void ToStringTest()
        {
            ConsoleOutputReceiver receiver = new ConsoleOutputReceiver();

            receiver.AddOutput("Hello, World!");
            receiver.AddOutput("See you!");

            receiver.Flush();

            Assert.Equal("Hello, World!\r\nSee you!\r\n",
                         receiver.ToString());
        }
示例#23
0
        static async Task <string> Shell(DeviceData device, params string[] cmds)
        {
            if (device == null)
            {
                return(null);
            }

            ConsoleOutputReceiver receiver = new ConsoleOutputReceiver();
            await AdbClient.Instance.ExecuteRemoteCommandAsync(string.Join(";", cmds), device, receiver, CancellationToken.None, 1000);

            return(receiver.ToString());
        }
        private void closeApp()
        {
            if (device == null)
            {
                return;
            }
            string command1  = @"am force-stop com.example.mediapipemultihandstrackingapp";
            var    receiver1 = new ConsoleOutputReceiver();

            adbClient.ExecuteRemoteCommand(command1, device, receiver1);
            Debug.Log("Stop remote app result: " + receiver1.ToString());
        }
        public void ToStringIgnoredLineTest2()
        {
            ConsoleOutputReceiver receiver = new ConsoleOutputReceiver();

            receiver.AddOutput("Hello, World!");
            receiver.AddOutput("$See you!");

            receiver.Flush();

            Assert.AreEqual("Hello, World!\r\n",
                            receiver.ToString());
        }
示例#26
0
        private void Button8_Click(object sender, EventArgs e)
        {
            var          device       = AdbClient.Instance.GetDevices().First();
            var          receiver     = new ConsoleOutputReceiver();
            DialogResult dialogResult = MessageBox.Show("Be sure to execute only trusted apps. Run?", "Run", MessageBoxButtons.YesNo);

            if (dialogResult == DialogResult.Yes)
            {
                AdbClient.Instance.ExecuteRemoteCommand("monkey -p " + textBox3.Text + " -c android.intent.category.LAUNCHER 1", device, receiver);
                MessageBox.Show(device.Name + " says:\n \n" + receiver.ToString());
            }
        }
示例#27
0
        private void Button9_Click(object sender, EventArgs e)
        {
            var          device       = AdbClient.Instance.GetDevices().First();
            var          receiver     = new ConsoleOutputReceiver();
            DialogResult dialogResult = MessageBox.Show("Be sure to know what you are doing. Kill?", "Run", MessageBoxButtons.YesNo);

            if (dialogResult == DialogResult.Yes)
            {
                AdbClient.Instance.ExecuteRemoteCommand("am force-stop --user 0 " + textBox3.Text, device, receiver);
                MessageBox.Show(device.Name + " says:\n \n" + receiver.ToString());
            }
        }
示例#28
0
        //public IEnumerable<IEntry> GetEntries(string path)
        //{
        //    using (SyncService service = new SyncService(this.deviceData))
        //    {
        //        return service.GetDirectoryListing(path).OrderBy(f => f.Path).Select(f => new AdbEntry(this, f, path));
        //    }
        //}

        //public IEnumerable<IEntry> GetFolders(string path)
        //{
        //    using (SyncService service = new SyncService(this.deviceData))
        //    {
        //        return service.GetDirectoryListing(path).Where(f => f.Path != "." && f.Path != "..").Select(f => new AdbEntry(this, f, path)).Where(e => e.IsDirectory);
        //    }
        //}

        //public void Pull(string src, string dest)
        //{
        //    using (FileStream stream = File.Create(dest))
        //    {
        //        using (SyncService service = new SyncService(this.deviceData))
        //        {
        //            CancellationToken token;
        //            service.Pull(src, stream, null, token);
        //        }
        //    }
        //}

        //public void Pull(string path, Stream stream)
        //{
        //    using (SyncService service = new SyncService(this.deviceData))
        //    {
        //        CancellationToken token;
        //        service.Pull(path, stream, null, token);
        //    }
        //}

        //public void Push(Stream stream, string path)
        //{
        //    using (SyncService service = new SyncService(this.deviceData))
        //    {
        //        CancellationToken token;
        //        service.Push(stream, path, 0x777, DateTime.Now, null, token);
        //    }
        //}

        //public void Push(string src, string dest)
        //{
        //    string path = UnixPath.Combine(dest, Path.GetFileName(src));
        //    PushRecursive(src, path);
        //}

        //private void PushRecursive(string src, string dest)
        //{
        //    if (File.Exists(src))
        //    {
        //        using (FileStream stream = File.OpenRead(src))
        //        {
        //            using (SyncService service = new SyncService(this.deviceData))
        //            {
        //                CancellationToken token;
        //                service.Push(stream, dest, 0x777, DateTime.Now, null, token);
        //            }
        //        }
        //    }
        //    else if (Directory.Exists(src))
        //    {
        //        CreateFolder(dest);
        //        foreach (string entry in Directory.EnumerateFileSystemEntries(src))
        //        {
        //            string path = UnixPath.Combine(dest, Path.GetFileName(entry));
        //            PushRecursive(entry, path);
        //        }
        //    }
        //}

        //public bool HasDeviceInfo
        //{
        //    get { return true; }
        //}

        //public Dictionary<string, string> GetDeviceInfo()
        //{
        //    Dictionary<string, string> deviceInfo = null;
        //    try
        //    {
        //        //deviceInfo.Product = ExcecuteCommandResult("getprop ro.build.product").Trim();
        //        //deviceInfo.System = "Android";
        //        //deviceInfo.Version = ExcecuteCommandResult("getprop ro.build.version.release").Trim();
        //        //deviceInfo.Release = ExcecuteCommandResult("getprop ro.build.version.sdk").Trim();
        //        //deviceInfo.BuildDate = ExcecuteCommandResult("getprop ro.build.date").Trim();
        //        //deviceInfo.BuildId = ExcecuteCommandResult("getprop ro.build.id").Trim();
        //        //deviceInfo.Hardware = ExcecuteCommandResult("getprop ro.hardware").Trim();
        //        //deviceInfo.Board = ExcecuteCommandResult("getprop ro.product.board").Trim();
        //        //deviceInfo.CPU = ExcecuteCommandResult("getprop ro.product.cpu.abi").Trim();
        //        //deviceInfo.Device = ExcecuteCommandResult("getprop ro.product.device").Trim();
        //        //deviceInfo.Model = ExcecuteCommandResult("getprop ro.product.model").Trim();
        //        //deviceInfo.OpenGl = ExcecuteCommandResult("getprop ro.opengles.version").Trim();
        //        //deviceInfo.Language = ExcecuteCommandResult("getprop ro.product.locale.language").Trim() + "-" + ExcecuteCommandResult("getprop ro.product.locale.region").Trim();
        //        //deviceInfo.Timezone = ExcecuteCommandResult("getprop persist.sys.timezone").Trim();
        //        //deviceInfo.Fingerprint = ExcecuteCommandResult("getprop ro.build.fingerprint").Trim();
        //        //deviceInfo.Fingerprint = ExcecuteCommandResult("getprop ro.build.fingerprint").Trim();
        //        //deviceInfo.Heapsize = ExcecuteCommandResult("getprop dalvik.vm.heapsize").Trim();

        //        deviceInfo = new Dictionary<string, string>();
        //        string prop = ExcecuteCommandResult("getprop");
        //        foreach (string line in prop.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries))
        //        {
        //            Match match = Regex.Match(line, @"\[(?<name>[^\]]+)\]: \[(?<value>[^\]]+)\]");
        //            if (match.Success)
        //            {
        //                string name = match.Groups["name"].Value;
        //                string value = match.Groups["value"].Value;
        //                deviceInfo.Add(name, value);
        //            }
        //        }
        //    }
        //    catch { }
        //    return deviceInfo;
        //}

        //public bool HasMemoryInfo
        //{
        //    get { return true; }
        //}

        //private bool useBusybox = true;
        //private bool useVmstat = true;

        //private const long Kilo = 1024;
        //private const long Mega = 1024 * 1024;
        //private const long Giga = 1024 * 1024 * 1024;

        //public Dictionary<string, DeviceMemoryInfo> GetMemoryInfo()
        //{
        //    Dictionary<string, DeviceMemoryInfo> deviceMemory = new Dictionary<string, DeviceMemoryInfo>();
        //    if (useBusybox)
        //    {
        //        try
        //        {
        //            // busybox free -m; vmstat -n 1
        //            string res = ExcecuteCommandResult("busybox free -m");
        //            Match match = Regex.Match(res, @"[^\n]*\nMem:\s+(?<total>\d+)\s+(?<used>\d+)\s+(?<free>\d+)");
        //            if (!match.Success)
        //            {
        //                throw new Exception("Parse free failed");
        //            }
        //            deviceMemory.Add("System", new DeviceMemoryInfo(
        //                long.Parse(match.Groups["total"].Value) * Mega,
        //                long.Parse(match.Groups["used"].Value) * Mega,
        //                long.Parse(match.Groups["free"].Value) * Mega));
        //        }
        //        catch
        //        {
        //            useBusybox = false;
        //        }
        //    }

        //    if (!useBusybox && useVmstat)
        //    {
        //        try
        //        {
        //            string res = ExcecuteCommandResult("vmstat -n 1");
        //            Match match = Regex.Match(res, @"[^\n]*\n[^\n]*\n\s*(?<r>\d+)\s+(?<b>\d+)\s+(?<free>\d+)\s+(?<mapped>\d+)\s+(?<anon>\d+)\s+(?<slab>\d+)");
        //            if (!match.Success)
        //            {
        //                throw new Exception("Parse vmstat failed");
        //            }

        //            deviceMemory.Add("System", new DeviceMemoryInfo (long.Parse(match.Groups["free"].Value)));
        //        }
        //        catch
        //        {
        //            useBusybox = false;
        //        }
        //    }

        //    try
        //    {
        //        string res = ExcecuteCommandResult("df");
        //        foreach (string line in res.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries))
        //        {
        //            if (line.StartsWith("/data"))
        //            {
        //                Match match = Regex.Match(line, @"\D*(?<size>[\d\.]+)(?<sizeUnit>[MKG])\s+(?<used>[\d\.]+)(?<usedUnit>[MKG])\s+(?<free>[\d\.]+)(?<freeUnit>[MKG])");
        //                if (match.Success)
        //                {
        //                    deviceMemory.Add("Local", new DeviceMemoryInfo(
        //                        GetSize(match, "size"),
        //                        GetSize(match, "used"),
        //                        GetSize(match, "free")));
        //                }
        //            }
        //            else if (line.StartsWith("/storage/sdcard0"))
        //            {
        //                Match match = Regex.Match(line, @"\D*(?<size>[\d\.]+)(?<sizeUnit>[MKG])\s+(?<used>[\d\.]+)(?<usedUnit>[MKG])\s+(?<free>[\d\.]+)(?<freeUnit>[MKG])");
        //                if (match.Success)
        //                {
        //                    deviceMemory.Add("SDCard", new DeviceMemoryInfo(
        //                        GetSize(match, "size"),
        //                        GetSize(match, "used"),
        //                        GetSize(match, "free")));
        //                }
        //            }
        //            else if (line.StartsWith("/storage/udisk"))
        //            {
        //                Match match = Regex.Match(line, @"\D*(?<size>[\d\.]+)(?<sizeUnit>[MKG])\s+(?<used>[\d\.]+)(?<usedUnit>[MKG])\s+(?<free>[\d\.]+)(?<freeUnit>[MKG])");
        //                if (match.Success)
        //                {
        //                    deviceMemory.Add("USB", new DeviceMemoryInfo(
        //                        GetSize(match, "size"),
        //                        GetSize(match, "used"),
        //                        GetSize(match, "free")));
        //                }
        //            }
        //        }

        //    }
        //    catch
        //    { }

        //    try
        //    {
        //        string res = ExcecuteCommandResult("dumpsys meminfo com.elektrobit.mobile.companion");
        //        foreach (string line in res.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries))
        //        {
        //            if (line.Trim().StartsWith("Native Heap"))
        //            {
        //                Match match = Regex.Match(line, @"\D*\d+\s+\d+\s+\d+\s+\d+\s+(?<size>\d+)\s+(?<used>\d+)\s+(?<free>\d+)");
        //                if (match.Success)
        //                {
        //                    deviceMemory.Add("AppNative", new DeviceMemoryInfo(
        //                        long.Parse(match.Groups["size"].Value) * Kilo,
        //                        long.Parse(match.Groups["used"].Value) * Kilo,
        //                        long.Parse(match.Groups["free"].Value) * Kilo));
        //                }
        //            }
        //            else if (line.Trim().StartsWith("Dalvik Heap"))
        //            {
        //                Match match = Regex.Match(line, @"\D*\d+\s+\d+\s+\d+\s+\d+\s+(?<size>\d+)\s+(?<used>\d+)\s+(?<free>\d+)");
        //                if (match.Success)
        //                {
        //                    deviceMemory.Add("AppDalvik", new DeviceMemoryInfo(
        //                        long.Parse(match.Groups["size"].Value) * Kilo,
        //                        long.Parse(match.Groups["used"].Value) * Kilo,
        //                        long.Parse(match.Groups["free"].Value) * Kilo));
        //                }
        //            }
        //        }
        //    }
        //    catch
        //    { }
        //    return deviceMemory;
        //}

        //private long GetSize(Match match, string group)
        //{
        //    string val = match.Groups[group].Value;
        //    double num = double.Parse(val, new CultureInfo("en-US"));
        //    string unit = match.Groups[group+"Unit"].Value;
        //    switch (unit)
        //    {
        //    case "K": num = num * Kilo; break;
        //    case "M": num = num * Mega; break;
        //    case "G": num = num * Giga; break;
        //    }
        //    return (long)Math.Ceiling(num);
        //}

        public void ExcecuteCommand(string cmd)
        {
            var receiver = new ConsoleOutputReceiver();

            client.ExecuteRemoteCommand(cmd, this.deviceData, receiver);
            string text = receiver.ToString();

            if (!string.IsNullOrEmpty(text))
            {
                throw new Exception(text);
            }
        }
示例#29
0
        private Point GetAdbScreenSize()
        {
            var receiver = new ConsoleOutputReceiver();

            this.client.ExecuteRemoteCommand("wm size", device, receiver);
            string[] strArr   = receiver.ToString().Split(' ')[2].Split('x');
            int[]    intArr   = Array.ConvertAll(strArr, Int32.Parse);
            var      endPoint = new Point(intArr[0], intArr[1]);

            log.Info("Resolution : " + endPoint.X + "x" + endPoint.Y);
            return(endPoint);
        }
示例#30
0
 public string SendCommand(string command, bool newReceiver = true)
 {
     if (currentDevice is null)
     {
         return(string.Empty);
     }
     if (newReceiver)
     {
         receiver = new ConsoleOutputReceiver();
     }
     AdbClient.Instance.ExecuteRemoteCommand(command, currentDevice.Data, receiver);
     return(receiver.ToString().Trim());
 }
示例#31
0
        public void ExecuteRemoteCommandTest()
        {
            var device = new DeviceData()
            {
                Serial = "169.254.109.177:5555",
                State = DeviceState.Online
            };

            var responses = new AdbResponse[]
            {
                AdbResponse.OK,
                AdbResponse.OK
            };

            var responseMessages = new string[] { };

            var requests = new string[]
            {
                "host:transport:169.254.109.177:5555",
                "shell:echo Hello, World"
            };

            byte[] streamData = Encoding.ASCII.GetBytes("Hello, World\r\n");
            MemoryStream shellStream = new MemoryStream(streamData);

            var receiver = new ConsoleOutputReceiver();

            this.RunTest(
                responses,
                responseMessages,
                requests,
                shellStream,
                () =>
                {
                    AdbClient.Instance.ExecuteRemoteCommand("echo Hello, World", device, receiver);
                });

            Assert.AreEqual("Hello, World\r\n", receiver.ToString());
        }
        /// <summary>
        /// Lists all processes running on the device.
        /// </summary>
        /// <param name="device">
        /// The device on which to list the processes that are running.
        /// </param>
        /// <returns>
        /// An <see cref="IEnumerable{AndroidProcess}"/> that will iterate over all
        /// processes that are currently running on the device.
        /// </returns>
        public static IEnumerable<AndroidProcess> ListProcesses(this DeviceData device)
        {
            // There are a couple of gotcha's when listing processes on an Android device.
            // One way would be to run ps and parse the output. However, the output of
            // ps differents from Android version to Android version, is not delimited, nor
            // entirely fixed length, and some of the fields can be empty, so it's almost impossible
            // to parse correctly.
            //
            // The alternative is to directly read the values in /proc/[pid], pretty much like ps
            // does (see https://android.googlesource.com/platform/system/core/+/master/toolbox/ps.c).
            //
            // The easiest way to do the directory listings would be to use the SyncService; unfortunately,
            // the sync service doesn't work very well with /proc/ so we're back to using ls and taking it
            // from there.
            List<AndroidProcess> processes = new List<AndroidProcess>();

            // List all processes by doing ls /proc/.
            // All subfolders which are completely numeric are PIDs
            ConsoleOutputReceiver receiver = new ConsoleOutputReceiver();
            device.ExecuteShellCommand("/system/bin/ls /proc/", receiver);

            Collection<int> pids = new Collection<int>();

            using (StringReader reader = new StringReader(receiver.ToString()))
            {
                while (reader.Peek() > 0)
                {
                    string line = reader.ReadLine();

                    if (!line.All(c => char.IsDigit(c)))
                    {
                        continue;
                    }

                    var pid = int.Parse(line);

                    pids.Add(pid);
                }
            }

            // For each pid, we can get /proc/[pid]/stat, which contains the process information in a well-defined
            // format - see http://man7.org/linux/man-pages/man5/proc.5.html.
            // Doing cat on each file one by one takes too much time. Doing cat on all of them at the same time doesn't work
            // either, because the command line would be too long.
            // So we do it 50 processes at at time.
            StringBuilder catBuilder = new StringBuilder();
            ProcessOutputReceiver processOutputReceiver = new ProcessOutputReceiver();

            for (int i = 0; i < pids.Count; i++)
            {
                if (i % 50 == 0)
                {
                    catBuilder.Clear();
                    catBuilder.Append("cat ");
                }

                catBuilder.Append($"/proc/{pids[i]}/stat ");

                if (i > 0 && (i % 50 == 0 || i == pids.Count - 1))
                {
                        device.ExecuteShellCommand(catBuilder.ToString(), processOutputReceiver);
                }
            }

            processOutputReceiver.Flush();

            return processOutputReceiver.Processes;
        }