標籤:
第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
老李推薦: 第8章4節《MonkeyRunner源碼剖析》MonkeyRunner啟動運行過程-啟動AndroidDebugBridge 2