通过cmd.exe来执行adb命令,可以进行一些命令组合,直接用adb.exe的话只能执行单个adb命令
这里要注意cmd 中的/c参数,指明此参数时,他将执行整个字符串中包含的命令并退出当前cmd运行环境
如:
命令:C:Windowssystem32>cmd /c E:WorkProjectslenovo_lmsalmsa-clientBinadb.exe devices | findstr "3"
3b2ac4c5 device
命令执行成功
当去掉/c时,将一直处于执行状态并不会退出(当通过下面的方法执行时WaitForExit方法将处于阻塞状态)
命令:C:Windowssystem32>cmd E:WorkProjectslenovo_lmsalmsa-clientBinadb.exe devices | findstr "3"
当去掉/c 与管道命令时,执行情况如下(同命令C:Windowssystem32>cmd结果一致)
命令:C:Windowssystem32>cmd E:WorkProjectslenovo_lmsalmsa-clientBinadb.exe devices
Microsoft Windows [Version 10.0.10586]
(c) 2015 Microsoft Corporation. All rights reserved.
所以,在代码中一定得注意/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(" ", response.ToArray()); if (data.EndsWith(" ")) { data = data.Remove(data.LastIndexOf(" ")); } return data;
}