Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 藍牙串口連線實作與疑難排解

編輯:關於 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 類別

上述程式碼中的 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 服務的裝置)成功連線的機率。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved