问题
I'm trying to run a rapid amount of adb shell commands. Basically, i want to start adb shell, and then run a bunch of commands in rapid succession. Can I reuse a Process in some way? I'd like to just start adb shell and change the command text at runtime.
The problem is with creating a separate process for each command spins up a lot of process and eventually adb craps out on me.
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:
When a device does not respond to shell commands issued via adb via Process, you can check the device state like follows:
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
来源:https://stackoverflow.com/questions/21144979/running-adb-shell-commands-rapidly-in-c-sharp-console-app