Repository navigation
Expand file tree
/
Copy pathAdbServer.java
More file actions
495 lines (439 loc) · 16.7 KB
/
Copy pathAdbServer.java
File metadata and controls
495 lines (439 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
/*
*
* MIT License
*
* Copyright (c) 2017 朱辉 https://blog.yeetor.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.yeetor.adb;
import com.android.ddmlib.*;
import com.android.ddmlib.TimeoutException;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import org.apache.log4j.Logger;
import javax.usb.*;
import javax.usb.event.UsbServicesEvent;
import javax.usb.event.UsbServicesListener;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.*;
public class AdbServer {
private static Logger logger = Logger.getLogger(AdbServer.class);
private static AdbServer server;
private String adbPath = null;
private String adbPlatformTools = "platform-tools";
List<AdbDevice> adbDeviceList = null;
List<IAdbServerListener> listeners = null;
AndroidDebugBridge adb = null;
private boolean success = false;
public static AdbServer server() {
if (server == null) {
server = new AdbServer();
}
return server;
}
private AdbServer() {
init();
}
/**
* 监听USB设备的状态
*/
public void listenUSB() {
adbDeviceList = new ArrayList<>();
UsbServices services = null;
try {
services = UsbHostManager.getUsbServices();
} catch (UsbException e) {
e.printStackTrace(); // TODO: LOG
}
services.addUsbServicesListener(new MyUSBListener());
System.out.println("AdbServer.listenUSB: 已开启USB设备监听...");
}
/**
* 监听ADB
*/
public void listenADB() {
new Thread() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
refreshAdbDeviceList();
}
}
}.start();
}
/**
* USB设备连接时调用
*/
private void onUsbDeviceConnected(UsbDevice usbDevice) {
logger.info(String.format("USB设备连接:idProduct(0x%x) idVendor(0x%x)", usbDevice.getUsbDeviceDescriptor().idProduct(), usbDevice.getUsbDeviceDescriptor().idVendor()));
List<AdbDevice> devices = checkAdbDevices(usbDevice);
devices.forEach(adbDevice -> onAdbDeviceConnected(adbDevice));
}
/**
* USB设备断开时调用
*/
private void onUsbDeviceDisConnected(UsbDevice usbDevice) {
logger.info(String.format("USB设备断开:idProduct(0x%x) idVendor(0x%x)", usbDevice.getUsbDeviceDescriptor().idProduct(), usbDevice.getUsbDeviceDescriptor().idVendor()));
List<AdbDevice> devices = checkAdbDevices(usbDevice);
devices.forEach(adbDevice -> onAdbDeviceDisConnected(adbDevice));
}
/**
* 发现安卓设备时调用
*/
private void onAdbDeviceConnected(AdbDevice adbDevice) {
/*
这部分代码是收到ADB设备连接事件时,将连接的adb设备加入到列表
但这样会与listenADB线程冲突,所以选择了后面的那个方案。仅仅将这个事件当做一个"立即刷新"的通知
这样带来的缺点就是,无法知道哪些设备是usb连接的
// 初始化IDevice
// TODO: 这一步,adb可能没能获取到连接的设备
IDevice[] iDevice = adb.getDevices();
for (IDevice device : iDevice) {
if (device.getSerialNumber().equals(adbDevice.getSerialNumber())) {
adbDevice.setIDevice(device);
break;
}
}
logger.info("Android设备连接:" + adbDevice.getSerialNumber());
// 添加在usb中检测到的设备
adbDeviceList.add(adbDevice);
*/
refreshAdbDeviceList();
}
/**
* 发现安卓设备断开时调用
*/
private void onAdbDeviceDisConnected(AdbDevice adbDevice) {
for (Iterator it = adbDeviceList.iterator(); it.hasNext(); ) {
AdbDevice device = (AdbDevice) it.next();
if (adbDevice.getUsbDevice() == device.getUsbDevice()) {
logger.info("Android设备断开:" + adbDevice.getSerialNumber());
it.remove();
listeners.forEach(l -> l.onAdbDeviceDisConnected(device));
}
}
}
/**
* 检测该UsbDevice是否是安卓设备
* @param usbDevice
* @return 检测到的安卓设备
*/
private List<AdbDevice> checkAdbDevices(UsbDevice usbDevice) {
List<AdbDevice> adbDevices = new ArrayList<>();
UsbDeviceDescriptor deviceDesc = usbDevice.getUsbDeviceDescriptor();
// Ignore devices from Non-ADB vendors
// 这步不要,要不然杂牌手机就没法检测到
// if (!AdbDevice.isAdbVendor(deviceDesc.idVendor())) return adbDevices;
// Check interfaces of device
UsbConfiguration config = usbDevice.getActiveUsbConfiguration();
for (UsbInterface iface: (List<UsbInterface>) config.getUsbInterfaces())
{
List<UsbEndpoint> endpoints = iface.getUsbEndpoints();
// Ignore interface if it does not have two endpoints
if (endpoints.size() != 2) continue;
// Ignore interface if it does not match the ADB specs
if (!AdbDevice.isAdbInterface(iface)) continue;
UsbEndpointDescriptor ed1 =
endpoints.get(0).getUsbEndpointDescriptor();
UsbEndpointDescriptor ed2 =
endpoints.get(1).getUsbEndpointDescriptor();
// Ignore interface if endpoints are not bulk endpoints
if (((ed1.bmAttributes() & UsbConst.ENDPOINT_TYPE_BULK) == 0) ||
((ed2.bmAttributes() & UsbConst.ENDPOINT_TYPE_BULK) == 0))
continue;
// Determine which endpoint is in and which is out. If both
// endpoints are in or out then ignore the interface
byte a1 = ed1.bEndpointAddress();
byte a2 = ed2.bEndpointAddress();
byte in, out;
if (((a1 & UsbConst.ENDPOINT_DIRECTION_IN) != 0) &&
((a2 & UsbConst.ENDPOINT_DIRECTION_IN) == 0)) {
in = a1;
out = a2;
} else if (((a2 & UsbConst.ENDPOINT_DIRECTION_IN) != 0) &&
((a1 & UsbConst.ENDPOINT_DIRECTION_IN) == 0)) {
out = a1;
in = a2;
} else {
continue;
}
adbDevices.add(new AdbDevice(usbDevice, iface, in, out));
}
return adbDevices;
}
/**
* 与adb同步设备状态
* why?有可能设备是通过wifi或bt连接,这样usb接口是检测不到的
*/
private void refreshAdbDeviceList() {
List<AdbDevice> tmpAdbDeviceList = new ArrayList<>(this.adbDeviceList);
IDevice[] iDevices = getIDevices();
// 添加新的adb设备
for (IDevice iDevice : iDevices) {
boolean exists = false;
for (AdbDevice adbDev : tmpAdbDeviceList) {
if (adbDev.getIDevice().getSerialNumber().equals(iDevice.getSerialNumber())) {
exists = true;
break;
}
}
// 如果在已有列表不存在,添加到已有列表
if (!exists) {
AdbDevice device = new AdbDevice(iDevice);
logger.info("Android设备连接:" + device.getSerialNumber());
this.adbDeviceList.add(device);
listeners.forEach(l -> l.onAdbDeviceConnected(device));
}
}
// 移除已断开的设备
for (AdbDevice adbDev : tmpAdbDeviceList) {
boolean exists = false;
for (IDevice iDevice : iDevices) {
if (adbDev.getIDevice().getSerialNumber().equals(iDevice.getSerialNumber())) {
exists = true;
break;
}
}
// 如果在已有列表不存在,添加到已有列表
if (!exists) {
onAdbDeviceDisConnected(adbDev);
}
}
}
private String getADBPath(){
if (adbPath == null){
adbPath = System.getenv("ANDROID_SDK_ROOT");
if(adbPath != null){
adbPath += File.separator + adbPlatformTools;
}else {
adbPath = "adb";
return adbPath;
}
}
adbPath += File.separator + "adb";
return adbPath;
}
private void init() {
AndroidDebugBridge.init(false);
adb = AndroidDebugBridge.createBridge(getADBPath(), true);
listeners = new ArrayList<>();
if (adb != null) {
if (waitForDeviceList()) {
success = true;
}
}
}
private boolean waitForDeviceList() {
int maxWaittingTime = 100;
int interval = 10;
while (!adb.hasInitialDeviceList()) {
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
break;
}
maxWaittingTime -= 1;
if (maxWaittingTime == 0) {
disconnectAdb();
return false;
}
}
return true;
}
void disconnectAdb() {
if (adb != null) {
adb = null;
}
success = false;
}
/**
* 获取ADB命令返回的设备列表
* @return IDevices
*/
public IDevice[] getIDevices() {
return adb.getDevices();
}
public List<AdbDevice> getDevices() {
return this.adbDeviceList;
}
public AdbDevice getDevice(String serialNumber) {
for (AdbDevice device : adbDeviceList) {
if (device.getSerialNumber().equals(serialNumber)) {
return device;
}
}
return null;
}
public AdbDevice getFirstDevice() {
if (adbDeviceList.size() > 0) {
return adbDeviceList.get(0);
}
return null;
}
public static String executeShellCommand(IDevice device, String command) {
CollectingOutputReceiver output = new CollectingOutputReceiver();
try {
device.executeShellCommand(command, output, 0);
} catch (TimeoutException e) {
e.printStackTrace();
} catch (AdbCommandRejectedException e) {
e.printStackTrace();
} catch (ShellCommandUnresponsiveException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return output.getOutput();
}
/**
* TODO: 添加自定义adb命令,原因是安卓手表的传输速度太慢,导致adb push超时错误
* @param device
* @return
*/
public String executePushFile(IDevice device, String src, String dst) {
final File adbFile = new File(AdbServer.server().adbPath);
final SettableFuture future = SettableFuture.create();
(new Thread(new Runnable() {
public void run() {
ProcessBuilder pb = new ProcessBuilder(new String[]{adbFile.getPath(), "-s", device.getSerialNumber(), "push", src, dst});
pb.redirectErrorStream(true);
Process p = null;
try {
p = pb.start();
} catch (IOException e) {
future.setException(e);
return;
}
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
try {
String line;
try {
while((line = br.readLine()) != null) {
sb.append(line);
}
future.set(sb.toString());
return;
} catch (IOException ex) {
future.setException(ex);
return;
}
} finally {
try {
br.close();
} catch (IOException ex) {
future.setException(ex);
}
}
}
}, "Obtaining adb version")).start();
String s = "";
try {
s = (String) future.get(30, TimeUnit.SECONDS);
} catch (Exception e) {
return null;
}
return s;
}
private ListenableFuture<List<AdbForward>> executeGetForwardList() {
final File adbFile = new File(AdbServer.server().adbPath);
final SettableFuture future = SettableFuture.create();
(new Thread(new Runnable() {
public void run() {
ProcessBuilder pb = new ProcessBuilder(new String[]{adbFile.getPath(), "forward", "--list"});
pb.redirectErrorStream(true);
Process p = null;
try {
p = pb.start();
} catch (IOException e) {
future.setException(e);
return;
}
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
try {
String line;
try {
List<AdbForward> list = new ArrayList<AdbForward>();
while((line = br.readLine()) != null) {
//64b2b4d9 tcp:555 localabstract:shit
AdbForward forward = new AdbForward(line);
if (forward.isForward()) {
list.add(forward);
}
}
future.set(list);
return;
} catch (IOException ex) {
future.setException(ex);
return;
}
} finally {
try {
br.close();
} catch (IOException ex) {
future.setException(ex);
}
}
}
}, "Obtaining adb version")).start();
return future;
}
public AdbForward[] getForwardList() {
ListenableFuture<List<AdbForward>> future = executeGetForwardList();
try {
List<AdbForward> s = future.get(1, TimeUnit.SECONDS);
AdbForward[] ret = new AdbForward[s.size()];
s.toArray(ret);
return ret;
} catch (Exception ex) {
ex.printStackTrace();
}
return new AdbForward[0];
}
public void addListener(IAdbServerListener listener) {
this.listeners.add(listener);
}
class MyUSBListener implements UsbServicesListener {
@Override
public void usbDeviceAttached(UsbServicesEvent usbServicesEvent) {
UsbDevice device = usbServicesEvent.getUsbDevice();
if (!device.isUsbHub()) {
onUsbDeviceConnected(device);
}
}
@Override
public void usbDeviceDetached(UsbServicesEvent usbServicesEvent) {
UsbDevice device = usbServicesEvent.getUsbDevice();
if (!device.isUsbHub()) {
onUsbDeviceDisConnected(device);
}
}
}
}