如何知道什么时候Android设备插入USB端口?什么时候、端口、设备、Android

2023-09-06 11:27:32 作者:你我终年不遇

我如何判断一个Android设备插入到USB端口?我已经看到了,当检测到任何USB设备插入许多code样品,但我不能使用。我需要能够检测到Android设备。

How can I tell if an Android device is plugged in to a USB port? I've seen many code samples that detect when any USB device is plugged in, but I can't use that. I need to be able to detect an Android device.

推荐答案

问题我也不清楚,你有没有发现每一个Android设备,还是要检测只是你的私有设备?

Question isn't clear to me, do you have to detect every Android device, or you want to detect just your private device?

不过,这可能不是你在寻找,但你可以尝试最简单的方法是调用命令的 ADB设备的对USB设备连接事件,并解析输出。我不能给太多code,现在,因为时间有限,我也有,但看看 了WinUSB C#

Though, this may not be what are you searching for, but the easiest approach you could try would be to invoke command adb devices on USB device connection event and parse the output. I can't give much code right now, because of limited time I have, but take a look at WinUSB C#

您可以启动过程,并解析其输出。

You can start process and parse its output.

System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
psi.FileName = @"C:\Windows\System32\cmd.exe";
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.RedirectStandardInput = true;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;

System.Diagnostics.Process p = new Process();
p.StartInfo = psi;
p.OutputDataReceived += p_DataReceived;
p.EnableRaisingEvents = true;
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();

p.StandardInput.WriteLine("adb devices");
p.StandardInput.WriteLine("exit");
p.WaitForExit();

static void p_DataReceived(object sender, DataReceivedEventArgs e)
{
// Manipulate received data here
        Console.WriteLine(e.Data);
// if no devices, then there will be only "List of devices attached: "
}

再一次,这只是一个快速的例子,应该有一个更好的解决方案。您可以在连接时检查设备ID,但它使另一个问题 - 如何知道这个ID是一个Android设备的ID

Once again, it's only a fast example and there should be a better solution for it. You could check Device ID upon connection, but it makes another problem - how to know that this ID is ID of an Android device?

编辑:您还需要亚行的可执​​行文件添加到您的PATH环境变量

You also have to add ADB executable to your PATH environmental variable.

EDIT2:如果您不想依赖于路径,您可以提供亚行与您的应用程序和应用程序的目录中运行它,以得到它 Application.StartupPath

If you don't want to rely on PATH, you could provide ADB with your application and run it from app's directory, getting it with Application.StartupPath

EDIT3:的另一个缺点是,您必须启用USB调试在你的Andr​​oid设备之前,亚行可以检测到它

Another drawback is that you have to enable USB Debugging in your Android device before ADB can detect it.