編輯:中階開發
整個 DDMS 裡最能體現 Android NIO 框架的,莫過於 MonitorThread.java 這支檔案。PC 與 Android 手機之間的同步機制,以及 NIO 非阻塞編程的精隨,幾乎都濃縮在這裡。
final class MonitorThread extends Thread {
private static final int CLIENT_READY = 2;
private static final int CLIENT_DISCONNECTED = 3;
private volatile boolean mQuit = false;
private ArrayList<Client> mClientList; // 用陣列保存客戶端資訊
private Selector mSelector;
private HashMap<Integer, ChunkHandler> mHandlerMap;
private ServerSocketChannel mDebugSelectedChan; // 一個用於除錯的伺服器通道
private int mNewDebugSelectedPort;
private int mDebugSelectedPort = -1;
private Client mSelectedClient = null;
private static MonitorThread mInstance;
private MonitorThread() {
super("Monitor");
mClientList = new ArrayList<Client>();
mHandlerMap = new HashMap<Integer, ChunkHandler>();
mNewDebugSelectedPort = DdmPreferences.getSelectedDebugPort();
}
static MonitorThread createInstance() { // 建立實例
return mInstance = new MonitorThread();
}
static MonitorThread getInstance() { // 取得實例
return mInstance;
}
synchronized void setDebugSelectedPort(int port) throws IllegalStateException {
if (mInstance == null) return;
if (androidDebugBridge.getClientSupport() == false) return;
if (mDebugSelectedChan != null) {
Log.d("ddms", "Changing debug-selected port to " + port);
mNewDebugSelectedPort = port;
wakeup(); // 喚醒所有 Selector
} else {
// 改設定 mNewDebugSelectedPort 而非 mDebugSelectedPort,
// 讓它能在下一輪自動生效
mNewDebugSelectedPort = port;
}
}
synchronized void setSelectedClient(Client selectedClient) {
if (mInstance == null) return;
if (mSelectedClient != selectedClient) {
Client oldClient = mSelectedClient;
mSelectedClient = selectedClient;
if (oldClient != null) oldClient.update(Client.CHANGE_PORT);
if (mSelectedClient != null) mSelectedClient.update(Client.CHANGE_PORT);
}
}
Client getSelectedClient() { return mSelectedClient; }
boolean getRetryOnBadHandshake() { return true; }
Client[] getClients() {
synchronized (mClientList) {
return mClientList.toArray(new Client[0]);
}
}
synchronized void registerChunkHandler(int type, ChunkHandler handler) {
if (mInstance == null) return;
synchronized (mHandlerMap) {
if (mHandlerMap.get(type) == null) {
mHandlerMap.put(type, handler);
}
}
}
@Override
public void run() { // 本類別的主要線程
Log.d("ddms", "Monitor is up");
try {
mSelector = Selector.open();
} catch (IOException ioe) {
Log.logAndDisplay(LogLevel.ERROR, "ddms",
"Failed to initialize Monitor Thread: " + ioe.getMessage());
return;
}
while (!mQuit) {
try {
synchronized (mClientList) { }
try {
if (androidDebugBridge.getClientSupport()) {
if ((mDebugSelectedChan == null ||
mNewDebugSelectedPort != mDebugSelectedPort) &&
mNewDebugSelectedPort != -1) {
if (reopenDebugSelectedPort()) {
mDebugSelectedPort = mNewDebugSelectedPort;
}
}
}
} catch (IOException ioe) {
Log.e("ddms", "Failed to reopen debug port for Selected Client to: "
+ mNewDebugSelectedPort);
Log.e("ddms", ioe);
mNewDebugSelectedPort = mDebugSelectedPort; // no retry
}
int count;
try {
count = mSelector.select();
} catch (IOException ioe) {
ioe.printStackTrace();
continue;
} catch (CancelledKeyException cke) {
continue;
}
if (count == 0) continue;
// 這裡的寫法並不理想:因為這段 NIO 是跑在 PC 端的 DDMS,
// 問題不明顯,但把輪詢塞進同一個 while 裡效率不高,CPU 佔用容易飆高。
Set<SelectionKey> keys = mSelector.selectedKeys();
Iterator<SelectionKey> iter = keys.iterator(); // 用迭代器取得選擇鍵
while (iter.hasNext()) {
SelectionKey key = iter.next();
iter.remove();
try {
if (key.attachment() instanceof Client) {
processClientActivity(key);
} else if (key.attachment() instanceof Debugger) {
processDebuggerActivity(key);
} else if (key.attachment() instanceof MonitorThread) {
processDebugSelectedActivity(key);
} else {
Log.e("ddms", "unknown activity key");
}
} catch (Exception e) {
Log.e("ddms", "Exception during activity from Selector.");
Log.e("ddms", e);
}
}
} catch (Exception e) {
Log.e("ddms", "Exception MonitorThread.run()");
Log.e("ddms", e);
}
}
}
這裡有個細節值得記住:多執行緒環境下,ConcurrentHashMap 通常比 HashMap 更安全也更有效率,是相當值得推薦的替代品。
private void processClientActivity(SelectionKey key) {
Client client = (Client) key.attachment();
try {
if (key.isReadable() == false || key.isValid() == false) {
Log.d("ddms", "Invalid key from " + client + ". Dropping client.");
dropClient(client, true /* notify */);
return;
}
client.read();
JdwpPacket packet = client.getJdwpPacket();
while (packet != null) {
if (packet.isDdmPacket()) {
// 非主動回覆的 DDM 請求,直接交給 handler
assert !packet.isReply();
callHandler(client, packet, null);
packet.consume();
} else if (packet.isReply()
&& client.isResponseToUs(packet.getId()) != null) {
// 對先前 DDM 請求的回覆
ChunkHandler handler = client.isResponseToUs(packet.getId());
if (packet.isError()) {
client.packetFailed(packet);
} else if (packet.isEmpty()) {
Log.d("ddms", "Got empty reply for 0x"
+ Integer.toHexString(packet.getId()) + " from " + client);
} else {
callHandler(client, packet, handler);
}
packet.consume();
client.removeRequestId(packet.getId());
} else {
// 轉發給 debugger
client.forwardPacketToDebugger(packet);
}
packet = client.getJdwpPacket();
}
} catch (CancelledKeyException e) { // 這個異常一定要正確處理
dropClient(client, true /* notify */);
} catch (IOException ex) {
dropClient(client, true /* notify */);
} catch (Exception ex) {
Log.e("ddms", ex);
dropClient(client, true /* notify */);
if (ex instanceof BufferOverflowException) { // 可能是緩衝區溢出
Log.w("ddms", "Client data packet exceeded maximum buffer size " + client);
} else {
Log.e("ddms", ex);
}
}
}
private void callHandler(Client client, JdwpPacket packet, ChunkHandler handler) {
// 收到第一個 DDM 封包時,廣播「就緒」訊息
if (!client.ddmSeen()) broadcast(CLIENT_READY, client);
ByteBuffer buf = packet.getPayload();
int type = buf.getInt();
int length = buf.getInt();
boolean reply = true;
if (handler == null) {
// 不是回覆,找出誰需要它
synchronized (mHandlerMap) {
handler = mHandlerMap.get(type);
reply = false;
}
}
if (handler == null) {
Log.w("ddms", "Received unsupported chunk type "
+ ChunkHandler.name(type) + " (len=" + length + ")");
} else {
ByteBuffer ibuf = buf.slice();
ByteBuffer roBuf = ibuf.asReadOnlyBuffer(); // 強制唯讀
roBuf.order(ChunkHandler.CHUNK_ORDER);
synchronized (mClientList) {
handler.handleChunk(client, type, roBuf, reply, packet.getId());
}
}
}
synchronized void dropClient(Client client, boolean notify) {
if (mInstance == null) return;
synchronized (mClientList) {
if (mClientList.remove(client) == false) return;
}
client.close(notify);
broadcast(CLIENT_DISCONNECTED, client);
wakeup();
}
private void processDebuggerActivity(SelectionKey key) {
Debugger dbg = (Debugger) key.attachment();
try {
if (key.isAcceptable()) { // 處理 Server 回應這個事件
try {
acceptNewDebugger(dbg, null);
} catch (IOException ioe) {
Log.w("ddms", "debugger accept() failed");
}
} else if (key.isReadable()) { // 收到資料,可以讀取
processDebuggerData(key);
} else {
Log.d("ddm-debugger", "key in unknown state");
}
} catch (CancelledKeyException cke) {
// key 已被取消,可以忽略。NIO 的這個異常很多入門開發者容易忘記處理。
}
}
private void acceptNewDebugger(Debugger dbg, ServerSocketChannel acceptChan)
throws IOException { // 這裡用到了阻塞方式
synchronized (mClientList) {
SocketChannel chan;
if (acceptChan == null) chan = dbg.accept();
else chan = dbg.accept(acceptChan);
if (chan != null) {
chan.socket().setTcpNoDelay(true);
wakeup();
try {
chan.register(mSelector, SelectionKey.OP_READ, dbg);
} catch (IOException ioe) {
dbg.closeData();
throw ioe;
} catch (RuntimeException re) {
dbg.closeData();
throw re;
}
} else {
Log.w("ddms", "ignoring duplicate debugger");
}
}
}
private void processDebuggerData(SelectionKey key) {
Debugger dbg = (Debugger) key.attachment();
try {
dbg.read();
JdwpPacket packet = dbg.getJdwpPacket();
while (packet != null) {
dbg.forwardPacketToClient(packet);
packet = dbg.getJdwpPacket();
}
} catch (IOException ioe) {
Log.d("ddms", "Closing connection to debugger " + dbg);
dbg.closeData();
Client client = dbg.getClient();
if (client != null) {
// 一併回收客戶端連線,交由 DeviceMonitor 重開
client.getDeviceImpl().getMonitor()
.addClientToDropAndReopen(client, IDebugPortProvider.NO_STATIC_PORT);
}
}
}
private void wakeup() { mSelector.wakeup(); }
synchronized void quit() {
mQuit = true;
wakeup();
try {
this.join();
synchronized (mClientList) {
for (Client c : mClientList) {
c.close(false /* notify */);
broadcast(CLIENT_DISCONNECTED, c);
}
mClientList.clear();
}
if (mDebugSelectedChan != null) {
mDebugSelectedChan.close();
mDebugSelectedChan.socket().close();
mDebugSelectedChan = null;
}
mSelector.close();
} catch (InterruptedException IE) {
IE.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mInstance = null;
}
synchronized void addClient(Client client) {
if (mInstance == null) return;
synchronized (mClientList) {
mClientList.add(client);
try {
wakeup();
client.register(mSelector);
Debugger dbg = client.getDebugger();
if (dbg != null) dbg.registerListener(mSelector);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
private void broadcast(int event, Client client) {
HashSet<ChunkHandler> set;
synchronized (mHandlerMap) {
set = new HashSet<ChunkHandler>(mHandlerMap.values());
}
Iterator<ChunkHandler> iter = set.iterator();
while (iter.hasNext()) {
ChunkHandler handler = iter.next();
switch (event) {
case CLIENT_READY:
try {
handler.clientReady(client);
} catch (IOException ioe) {
// 這個 client 出問題了,下次再操作它時就會被剔掉,
// 這裡先吞下異常,假設稍後會善後。
Log.w("ddms", "Got exception while broadcasting 'ready'");
return;
}
break;
case CLIENT_DISCONNECTED:
handler.clientDisconnected(client);
break;
default:
throw new UnsupportedOperationException();
}
}
}
private boolean reopenDebugSelectedPort() throws IOException {
Log.d("ddms", "reopen debug-selected port: " + mNewDebugSelectedPort);
if (mDebugSelectedChan != null) mDebugSelectedChan.close();
mDebugSelectedChan = ServerSocketChannel.open();
mDebugSelectedChan.configureBlocking(false); // Selector 的必要條件
InetSocketAddress addr = new InetSocketAddress(
InetAddress.getByName("localhost"), mNewDebugSelectedPort);
mDebugSelectedChan.socket().setReuseAddress(true); // 啟用 SO_REUSEADDR
try {
mDebugSelectedChan.socket().bind(addr);
if (mSelectedClient != null) {
mSelectedClient.update(Client.CHANGE_PORT);
}
mDebugSelectedChan.register(mSelector, SelectionKey.OP_ACCEPT, this);
return true;
} catch (java.net.BindException e) {
displayDebugSelectedBindError(mNewDebugSelectedPort);
mDebugSelectedChan = null; // 不再嘗試重開
mNewDebugSelectedPort = -1;
return false;
}
}
private void processDebugSelectedActivity(SelectionKey key) {
assert key.isAcceptable();
ServerSocketChannel acceptChan = (ServerSocketChannel) key.channel();
if (mSelectedClient != null) {
Debugger dbg = mSelectedClient.getDebugger();
if (dbg != null) {
try {
acceptNewDebugger(dbg, acceptChan);
} catch (IOException ioe) {
// client 應該已經消失,繼續跑
}
return;
}
}
Log.w("ddms", "Connection on 'debug selected' port, but none selected");
try {
SocketChannel chan = acceptChan.accept();
chan.close();
} catch (IOException ioe) {
// 非預期情況,client 應該已消失,繼續跑
} catch (NotYetBoundException e) {
displayDebugSelectedBindError(mDebugSelectedPort);
}
}
private void displayDebugSelectedBindError(int port) {
String message = String.format(
"Could not open Selected VM debug port (%1$d). Make sure you do not have "
+ "another instance of DDMS or of the eclipse plugin running. If it's being "
+ "used by something else, choose a new port number in the preferences.", port);
Log.logAndDisplay(LogLevel.ERROR, "ddms", message);
}
}
從上面的實作可以看出一件事:Android 開原始碼中屬於 PC 端的部分品質並不算理想,不少地方是靠反覆打補丁硬撐起來的,某些習慣也談不上到位。
這個 NIO 範例牽涉的物件相當多——Client、Debugger、ChunkHandler、DeviceMonitor 彼此環環相扣,光看單一檔案很難拼出全貌。建議的作法是先畫出 UML 類別圖與時序圖,把「誰註冊了什麼事件、事件回來之後交給誰」這條線拉直,再回頭讀每個物件的細節,理解起來會清晰很多。
Android 多媒體框架 OpenCore 入門(一):PVPlayer、PVAuthor 與原始碼結構
本文為個人整理,重點在於快速建立 Android 早期多媒體框架 OpenCore 的整體輪廓,並說明它與 Android 其他模組的關係。 OpenCore 的定位 O
混合式應用程式模型打造 WebSphere Commerce 行動 App(上)
摘要:本文說明「混合式應用程式」(hybrid application)這個編程模型與其他行動方案差異在哪,並透過兩個實作案例,示範如何用它為 WebSphere Com
HTML 5 本地儲存實戰:讓行動 Web 應用擺脫 4KB 的枷鎖
HTML 5 最實用的新能力之一,就是把「用戶端儲存」這件事真正標準化。過去十幾年,Web 開發者只能把資料硬塞進 4KB 的 Cookie 裡;現在,透過一組再簡單不過
用 Android 與 XML 打造動態表單應用(下):畫面生成、驗證與提交
接續上篇,本文將說明如何把 XML 表單定義轉換成實際可操作的 Android 畫面,並完成資料驗證、背景傳輸與提交結果提示。 動態產生表單畫面 在 Android 中