我正在编写一个小型C#应用程序来收集在连接到计算机的Android设备上运行的应用程序的logcat文件。
我可以轻松启动logcat并让它将所需的行记录到特定的文本文件中。但是我试图阻止logcat记录的每个命令都不起作用。
在使用管理员权限运行我的应用时,我也尝试了我的解决方案。
这是我的代码:
static void Main(string[] args)
{
string choice;
string clearLogging = @"adb logcat -c";
string startLogging = @"adb logcat MyApp_LoggingTag:V AndroidRuntime:E *:S > C:\logcat.txt";
string adbDir = @"C:\Users\me\AppData\Local\Android\android-sdk\platform-tools\";
string clearCommand = adbDir + clearLogging;
string startLoggingCommand = adbDir + startLogging;
ProcessStartInfo startInfo = new ProcessStartInfo("cmd.exe", "/K " + clearCommand);
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardInput = true;
//Tried giving the cmd process elevated rights and then use logcat -c - didn't work
//startInfo.Verb = "runas";
Process logcatRunner = Process.Start(startInfo);
//This works!
logcatRunner.StandardInput.WriteLine(startLoggingCommand);
Console.WriteLine("Logging has started.");
Console.Write("Press Enter to stop logging....");
Console.ReadLine();
//-c doesn't work
//logcatRunner.StandardInput.WriteLine(clearCommand);
//Tried killing adb via the logcatRunner process - doesn't work.
//logcatRunner.StandardInput.WriteLine(@"taskkill -f /im ""adb.exe""");
//Tried killing my process - doesn't work - adb is still running and logcat is still writing logs
//logcatRunner.Kill();
Console.WriteLine("Logging has stopped.");
Console.Write(@"Enter any key");
choice = Console.ReadLine();
}
关闭上述申请后,adb仍在运行 所以我的问题是,成功启动adb和logcat后,如何以编程方式关闭它们?
答案 0 :(得分:1)
使用您的方法执行此操作非常复杂。您创建cmd
进程,然后在那里启动另一个进程(adb)。要杀死adb,你需要将CTRL + C发送到cmd,但由于CreateNoWindow=true
而不是那么容易。我建议另一种方法并直接运行adb,重定向其输出:
string adbPath = @"G:\Android\android-sdk\platform-tools\adb.exe";
ProcessStartInfo startInfo = new ProcessStartInfo(adbPath, "logcat MyApp_LoggingTag:V AndroidRuntime:E *:S");
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
// if you don't want to recreate it each time - choose another file mode, like FileMode.Append
using (var fs = new FileStream(@"C:\logcat.txt", FileMode.Create, FileAccess.Write, FileShare.Read)) {
using (var writer = new StreamWriter(fs)) {
Process logcatRunner = new Process();
logcatRunner.StartInfo = startInfo;
logcatRunner.EnableRaisingEvents = true;
logcatRunner.OutputDataReceived += (sender, args) => {
// Data null indicates end of output stream - don't write it
if (args.Data != null) {
writer.Write(args.Data);
// flush immediately if needed
writer.Flush();
}
};
logcatRunner.Start();
logcatRunner.BeginOutputReadLine();
Console.WriteLine("Logging started, press any key to stop");
Console.ReadKey();
logcatRunner.CancelOutputRead();
logcatRunner.Kill();
logcatRunner.WaitForExit();
}
}