老李推荐: 第8章4节《MonkeyRunner源码剖析》MonkeyRunner启动运行过程-启动AndroidDebugBridge 2
第81-86行,整个方法的主体就是创建一个”Device List Monitor”的线程。线程运行方法run直接调用DeviceMonitor的deviceMonitorLoop方法来进行无限循环监控设备状态了。
155 private void deviceMonitorLoop()
156 {
157 do
158 {
159 try
160 {
161 if (this.mMainAdbConnection == null) {
162 Log.d("DeviceMonitor", "Opening adb connection");
163 this.mMainAdbConnection =
openAdbConnection();
164 if (this.mMainAdbConnection == null) {
165 this.mConnectionAttempt += 1;
166 Log.e("DeviceMonitor", "Connection attempts: " + this.mConnectionAttempt);
167 if (this.mConnectionAttempt > 10) {
168 if (!this.mServer.startAdb()) {
169 this.mRestartAttemptCount += 1;
170 Log.e("DeviceMonitor", "adb restart attempts: " + this.mRestartAttemptCount);
171 }
172 else {
173 this.mRestartAttemptCount = 0;
174 }
175 }
176 waitABit();
177 } else {
178 Log.d("DeviceMonitor", "Connected to adb for device monitoring");
179 this.mConnectionAttempt = 0;
180 }
181 }
182
183 if ((this.mMainAdbConnection != null) &&
(!this.mMonitoring)) {
184 this.mMonitoring = sendDeviceListMonitoringRequest();
185 }
186
187 if (this.mMonitoring)
188 {
189 int length = readLength(this.mMainAdbConnection, this.mLengthBuffer);
190
191 if (length >= 0)
192 {
193 processIncomingDeviceData(length);
194
195
196 this.mInitialDeviceListDone = true;
197 }
198 }
199 }
200 catch (AsynchronousCloseException ace) {}catch (TimeoutException ioe)
201 {
202 handleExpectionInMonitorLoop(ioe);
203 } catch (IOException ioe) {
204 handleExpectionInMonitorLoop(ioe);
205 }
206 } while (!this.mQuit);
207 }
代码8-4-3 DeviceMonitor - deviceMonitorLoop
- 第一步:163行,如果还没有连接上的ADB服务器的话就先连接上
- 第二步: 168行,确保ADB服务器已经启动
- 第三步: 183-185行,往ADB服务器发送监控命令,监控所有连接上来的移除的设备
- 第四步: 处理所获得的监控设备列表
我们先看第一步,在上一节中我们已经看到ADB服务器的启动过程了,但是我们还没有看到ADB客户端是怎么连接上服务器的,一下的代码就是一个实例:
255 private SocketChannel openAdbConnection()
256 {
257 Log.d("DeviceMonitor", "Connecting to adb for Device List Monitoring...");
258
259 SocketChannel adbChannel = null;
260 try {
261 adbChannel =
SocketChannel.open(
AndroidDebugBridge.getSocketAddress());
262 adbChannel.socket().setTcpNoDelay(true);
263 }
264 catch (IOException e) {}
265
266 return adbChannel;
267 }
代码8-4-4 DeviceMonitor - openAdbConnection