2014-01-15 152 views
1

我試圖運行快速的adb shell命令。基本上,我想啓動adb shell,然後連續運行一堆命令。我能否以某種方式重用流程?我想要啓動adb shell並在運行時更改命令文本。在C#控制檯應用程序中快速運行ADB Shell命令

問題是,爲每個命令創建一個單獨的進程加快了很多進程,並最終adb在我身上。

static void Main(string[] args) 
    { 
     const string AdbBroadcast = "shell am broadcast <my_cmd>"; 


     int broacastIndex = 0; 
     while(true) 
     { 
      Console.WriteLine("Outputting " + broacastIndex); 

      System.Diagnostics.Process process = new System.Diagnostics.Process(); 
      System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); 
      startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; 
      startInfo.FileName = "adb"; 
      startInfo.Arguments = AdbBroadcast; 
      process.StartInfo = startInfo; 
      process.Start(); 

      process.WaitForExit(); 


      Thread.Sleep(250); 
      broacastIndex++; 

     } 

    } 
+1

我不知道這是否會與您的特定錯誤幫助,但是你應該調用。當你完成它時(在'WaitForExit'之後),對你的進程進行處理。如果這個循環有很多迭代,你可能會在操作系統級別用完處理句柄。處理過程應該釋放句柄,以便可以重複使用。 –

回答

0

當設備不響應​​通過外殼經由過程亞行發出的命令,你可以檢查設備狀態類似如下:

ProcessStartInfo lcmdInfo1; 

    lcmdInfo1 = new ProcessStartInfo(" adb.exe ", "get-state"); 
    lcmdInfo1.CreateNoWindow = true; 
    lcmdInfo1.RedirectStandardOutput = true; 
    lcmdInfo1.RedirectStandardError = true; 
    lcmdInfo1.UseShellExecute = false; 

    Process cmd2 = new Process(); 
    cmd2.StartInfo = lcmdInfo1; 

    var output = new StringBuilder(); 
    var error = new StringBuilder(); 

    cmd2.OutputDataReceived += (o, ef) => output.Append(ef.Data); 
    cmd2.ErrorDataReceived += (o, ef) => error.Append(ef.Data); 
    cmd2.Start(); 
    cmd2.BeginOutputReadLine(); 
    cmd2.BeginErrorReadLine(); 
    cmd2.WaitForExit(); 
    cmd2.Close(); 
    lresulterr1 = error.ToString(); 
    lresult1 = output.ToString(); 
    cmd2.Dispose(); 

    //sometimes there is an issue with a previously issued command that causes the device status to be 'Unknown'. Wait until the device status is 'device' 
    while (!lresult1.Contains("device")) 
    { 
     lcmdInfo1 = new ProcessStartInfo(" adb.exe ", "get-state"); 
     lcmdInfo1.CreateNoWindow = true; 
     lcmdInfo1.RedirectStandardOutput = true; 
     lcmdInfo1.RedirectStandardError = true; 
     lcmdInfo1.UseShellExecute = false; 

     cmd2 = new Process(); 
     cmd2.StartInfo = lcmdInfo1; 

     output = new StringBuilder(); 
     error = new StringBuilder(); 

     cmd2.OutputDataReceived += (o, ef) => output.Append(ef.Data); 
     cmd2.ErrorDataReceived += (o, ef) => error.Append(ef.Data); 
     cmd2.Start(); 
     cmd2.BeginOutputReadLine(); 
     cmd2.BeginErrorReadLine(); 
     cmd2.WaitForExit(); 
     cmd2.Close(); 
     lresulterr1 = error.ToString(); 
     lresult1 = output.ToString(); 
     cmd2.Dispose(); 
    } 
//now your device is ready. Go ahead and fire off the shell commands 
相關問題