经过cmd.exe来执行adb命令,能够进行一些命令组合,直接用adb.exe的话只能执行单个adb命令spa
这里要注意cmd 中的/c参数,指明此参数时,他将执行整个字符串中包含的命令并退出当前cmd运行环境线程
如:code
命令:C:\Windows\system32>cmd /c E:\Work\Projects\lenovo_lmsa\lmsa-client\Bin\adb.exe devices | findstr "3"
3b2ac4c5 deviceorm
命令执行成功blog
当去掉/c时,将一直处于执行状态并不会退出(当经过下面的方法执行时WaitForExit方法将处于阻塞状态)字符串
命令:C:\Windows\system32>cmd E:\Work\Projects\lenovo_lmsa\lmsa-client\Bin\adb.exe devices | findstr "3"get
当去掉/c 与管道命令时,执行状况以下(同命令C:\Windows\system32>cmd结果一致)cmd
命令:C:\Windows\system32>cmd E:\Work\Projects\lenovo_lmsa\lmsa-client\Bin\adb.exe devicesstring
Microsoft Windows [Version 10.0.10586]
(c) 2015 Microsoft Corporation. All rights reserved.it
因此,在代码中必定得注意/c参数的使用
我在代码中执行 adb install -s serial -r file.apk时,若是目标设备未链接,此adb命令会阻塞等待设备链接,此时线程会阻塞,因此我执行adb devices | findstr "serial" && adb adb install -s serial -r file.apk命令,先判断目标设备是否还链接,而后在装apk,能大大下降阻塞的几率
方法调用代码片断(当命令较复杂时,最好用括号括起来,好比有路径什么的时候,不用括号把命令括起来,命令解析会失败)
string exe = System.IO.Path.Combine(Environment.SystemDirectory, "cmd.exe"); string targetCmd = string.Format("/c (\"{0}\" devices | findstr \"{1}\" && \"{0}\" -s \"{1}\" {2})" , System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"adb.exe") , deviceId ,sourceCommand);
Process方法代码:
public string Do(string exe, string command, int timeout)
{
List<string> response = new List<string>(); List<string> output = new List<string>(); List<string> error = new List<string>(); Process process = new Process(); process.StartInfo.FileName = exe; process.StartInfo.Arguments = command; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.CreateNoWindow = true; process.EnableRaisingEvents = true; System.IO.FileInfo file = new System.IO.FileInfo(exe); process.StartInfo.WorkingDirectory = file.Directory.FullName; process.OutputDataReceived += (object sender, System.Diagnostics.DataReceivedEventArgs e) => Redirected(output, sender, e); process.ErrorDataReceived += (object sender, System.Diagnostics.DataReceivedEventArgs e) => Redirected(error, sender, e); process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); bool exited = process.WaitForExit(timeout); if (!exited) { process.Kill(); response.Add("Error: timed out"); } response.AddRange(output); response.AddRange(error);
string data = String.Join("\r\n", response.ToArray()); if (data.EndsWith("\r\n")) { data = data.Remove(data.LastIndexOf("\r\n")); } return data;
}