最近的工作是Android驱动开发,时常需要使用adb shell命令来查询节点下面的很多信息
首先所有的adb shell命令是以ArrayList的格式传入的,查询的结果也是以ArrayList的形式扔出去的
其次C#实际上是调用本地系统应用实现的adb shell命令的执行,所以我们最好的是使用process这个类来实现
最后确保的是adb工具在C:\Windows目录下面
// new process对象
System.Diagnostics.Process p = new System.Diagnostics.Process();
// 设置属性
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
String command = string.Empty;
// 同时执行多条adb shell命令
for (int i = 0; i < commad_array.Count; i++) {
if (i == commad_array.Count - 1) {
command += "adb shell " + commad_array[i];
} else {
command += "adb shell " + commad_array[i] + "&";
}
}
p.StartInfo.Arguments = "/c " + command;
// 开启process线程
p.Start();
// 获取返回结果,这个是最简单的字符串的形式返回,现在试试以其他的形式去读取返回值的结果。
string str = string.Empty;
StreamReader readerout = p.StandardOutput;
string line = string.Empty;
while (!readerout.EndOfStream) {
line = readerout.ReadLine();
//Console.WriteLine(line);
//将得到的结果写入到excle中
excut_result.Add(line);
}
p.WaitForExit();
p.Close();
return excut_result;
}
前提是手机必须连接,当手机未连接的时候,查询不到结果值,可以以此条件来判断手机是否连接,在p.Start()这个函数的地方最好加上try catch来捕捉异常
简单的demo程序如下所示:
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c adb shell cat /proc/gesture_state";
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string outtr = p.StandardOutput.ReadToEnd();
MessageBox.Show(outtr);
p.Close();
主要使用的还是一个Process的一个来实现的。
本文介绍了在C#中如何执行adb shell命令,用于Android驱动开发中的设备查询。通过使用ArrayList传递命令,并利用Process类执行adb命令。同时强调了adb工具需放在C:Windows目录下,且需确保手机已连接,可以通过异常处理判断手机连接状态。
326

被折叠的 条评论
为什么被折叠?



