安卓手机和.NET之间的简单交互
我们通常都了解,安卓手机作为移动端和电脑PC端的连接在.NET环境下用的最多的是ADB。没错,今天做的一个小测试中,使用到了友好的插件,在此记录,作以分享。
首先怎样解决PC端和安卓手机的连接?
参考:
- http://blog.csdn.net/zhongchengxi/article/details/73655757
- http://blog.csdn.net/ynnmnm/article/details/38415221
上面的两篇博客都优秀的向我们展示了ADB的基本用法。
现在是时候解决.NET环境下怎么使用ADB与安卓手机连接?
有两种思路:
1.既然可以使用命令行去操作ADB从而实现对安卓手机基本信息的获取和基本功能的控制,那么完全可以用同样的方法将其使用在.NET的环境下即可。在C#中使用Process类从而相当于操作命令行。
Process p = new Process();//创建进程对象
p.StartInfo.FileName = "cmd.exe";//设定需要执行的命令
// startInfo.Arguments = "/C " + command;//“/C”表示执行完命令后马上退出
p.StartInfo.UseShellExecute = false;//不使用系统外壳程序启动
p.StartInfo.RedirectStandardInput = true;//可以重定向输入
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;//不创建窗口
p.Start();
2.使用VS中的插件与ADB结合使用。
- 下载插件在VS的当前项目中
- 简单的使用案例
//Starting the adb server
AdbServer server = new AdbServer();
var result = server.StartServer(@"C:\Program Files (x86)\android-sdk\platform-tools\adb.exe", restartServerIfNewer: false);
//List all Android devices currently connected
var devices = AdbClient.Instance.GetDevices();
foreach(var device in devices)
{
Console.WriteLine(device.Name);
}
//Subscribe for events when devices connect/disconnect
void Test()
{
var monitor new DeviceMonitor(new AdbSocket(new IPEndPoint(IPAddress.Loopback, AdbClient.AdbServerPort)));
monitor.DeviceConnected += this.OnDeviceConnected;
monitor.Start();
}
void OnDeviceConnected(object sender, DeviceDataEventArgs e)
{
Console.WriteLine($"The device {e.Device.Name} has connected to this PC");
}
//Manage applications
void InstallApplication()
{
var device = AdbClient.Instance.GetDevices().First();
PackageManager manager = new PackageManager(device);
manager.InstallPackage(@"C:\Users\me\Documents\mypackage.apk", reinstall: false);
}
//Send or receive files
void DownloadFile()
{
var device = AdbClient.Instance.GetDevices().First();
using (SyncService service = new SyncService(new AdbSocket(new IPEndPoint(IPAddress.Loopback, AdbClient.AdbServerPort)), device))
using (Stream stream = File.OpenWrite(@"C:\MyFile.txt"))
{
service.Pull("/data/local/tmp/MyFile.txt", stream, null, CancellationToken.None);
}
}
void UploadFile()
{
var device = AdbClient.Instance.GetDevices().First();
using (SyncService service = new SyncService(new AdbSocket(new IPEndPoint(IPAddress.Loopback, AdbClient.AdbServerPort)), device))
using (Stream stream = File.OpenRead(@"C:\MyFile.txt"))
{
service.Push(stream, "/data/local/tmp/MyFile.txt", 444, DateTime.Now, null, CancellationToken.None);
}
}
//Run shell commands
void EchoTest()
{
var device = AdbClient.Instance.GetDevices().First();
var receiver = new ConsoleOutputReceiver();
AdbClient.Instance.ExecuteRemoteCommand("echo Hello, World", device, receiver);
Console.WriteLine("The device responded:");
Console.WriteLine(receiver.ToString());
}
以上这些操作大致满足了我们PC端和安卓手机的基本交互,如果想进一步深入实现更多的功能,有两种方式,不难猜出,一种是执行命令行操作在.NET环境下,另一种是了解插件下类分装的相关方法和成员。
分享有价值的东西!