編輯:關於 Android 程式設計
在開發 Android 藍牙串口(RFCOMM)連線時,許多人會直覺地使用 createRfcommSocketToServiceRecord(MY_UUID) 建立 socket,再呼叫 connect()。然而實務上,BluetoothSocket.connect() 經常拋出各種錯誤,導致連線失敗。本文分享一套更為健壯的連線策略。
標準寫法如下:
BluetoothSocket tmp = null;
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.e(TAG, "create() failed", e);
}
// 接著呼叫 tmp.connect()
問題在於,connect() 本身就容易失敗,尤其是當裝置使用的 RFCOMM 通道號並非固定的服務 UUID 時。
由於藍牙裝置共有 30 個 RFCOMM 通道(1 到 30),一個雖然看似笨拙卻相當有效的做法是——逐一嘗試每個通道路,同時兼顧 Secure 與 Insecure 兩種連線模式:
private class ConnectThread extends Thread {
private BluetoothSocket mmSocket;
private BluetoothDevice mmDevice;
ImprovedBluetoothDevice improvedBluetoothDevice;
public ConnectThread(BluetoothDevice device) {
mmDevice = device;
improvedBluetoothDevice = new ImprovedBluetoothDevice(device);
}
public void run() {
mAdapter.cancelDiscovery(); // 取消探索,避免拖慢連線
String connectionType = "?";
// 逐一嘗試 1~30 通道
for (int port = 1; port < 31; port++) {
try {
connectionType = "Secure";
BluetoothSocket s = improvedBluetoothDevice.createRfcommSocket(port);
s.connect();
mmSocket = s;
} catch (Exception ex) {
Log.e(TAG, ex.toString());
mmSocket = null;
try {
connectionType = "Insecure";
BluetoothSocket s = improvedBluetoothDevice.createInsecureRfcommSocket(port);
s.connect();
mmSocket = s;
} catch (Exception ex2) {
Log.e(TAG, ex2.toString());
mmSocket = null;
}
}
if (mmSocket != null) {
Log.d(TAG, "Connection succeeded with " + connectionType + " on port " + port);
break;
}
}
// 若仍未連上,退回使用標準 UUID 方式
if (mmSocket == null) {
try {
mmSocket = improvedBluetoothDevice.createRfcommSocketToServiceRecord(MY_UUID);
mmSocket.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
connected(mmSocket, mmDevice); // 連線成功後啟動資料傳輸
}
public void cancel() {
try {
if (mmSocket != null) mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
上述程式碼中的 ImprovedBluetoothDevice 是一個包裝類,它透過 Java 反射(Reflection)機制,把 BluetoothDevice 原本隱藏(非 public)的內部方法——例如指定通道號的 createRfcommSocket(int) 與 createInsecureRfcommSocket(int)——「暴露」成一般可用的方法。其核心概念如下:
// 透過反射取得隱藏方法
private static final Method _createRfcommSocket =
getMethod(BluetoothDevice.class, "createRfcommSocket", new Class[] { int.class });
private static final Method _createInsecureRfcommSocket =
getMethod(BluetoothDevice.class, "createInsecureRfcommSocket", new Class[] { int.class });
// 呼叫時包裝成一般方法
public BluetoothSocket createRfcommSocket(int channel) throws Exception {
if (_createRfcommSocket == null) throw new NoSuchMethodException("createRfcommSocket");
try {
return (BluetoothSocket) _createRfcommSocket.invoke(mDevice, channel);
} catch (InvocationTargetException tex) {
if (tex.getCause() instanceof Exception) throw (Exception) tex.getCause();
else throw tex;
}
}
這個類別除了 RFCOMM,也提供了 L2CAP socket、設定 PIN 碼(setPin)與通行金鑰(setPasskey)等進階能力,並以 LGPL 授權開源釋出。
藍牙串口連線的穩健性一直是開發痛點。透過「逐一嘗試通道路 + Secure/Insecure 雙模式 + 反射呼叫隱藏 API」的組合策略,能有效提高與各類藍牙裝置(尤其是缺乏標準 UUID 服務的裝置)成功連線的機率。
Android 開發實作:用 Camera 類控制相機拍照並自動對焦
現在的手機相機動輒上千萬畫素,有些甚至支援獨立對焦、光學變焦等以往只有單眼相機才有的功能。為了充分利用這些硬體能力,Android 提供了 Camera 類讓開發者自行控
仿 QQ 的滑動選單:依 ItemViewType 給不同項目不同操作
上一篇介紹了如何用 SwipeMenuListView 這個開源庫做出滑動選單。本篇進一步探討一個更進階的問題:如何讓清單中不同的項目顯示不同的選單?以下以「仿 QQ 標
ViewPager 添加標題欄:PagerTabStrip 與 PagerTitleStrip 用法對比
使用 ViewPager 時,我們常希望每個頁面上方帶一個標題。Google 在 v4 包中提供了兩個現成控件——PagerTabStrip 與 PagerTitleSt
Android Activity 屏幕切換動畫:左右滑動效果實作
Activity 之間的切換效果,可以透過 overridePendingTransition 指定進入與退出動畫。自 Android 2.0 起,開發者能在 start