經過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;
}