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

Android 藍牙開發全解析:權限、裝置發現、配對與 RFCOMM 通信

編輯:關於 Android 程式設計

藍牙開發可以拆成四個階段:申請權限、控制本機藍牙模組、搜尋並配對裝置、建立 Socket 傳資料。本文依序說明,並附上各階段的關鍵程式碼。

一、權限

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

從 Android 12(API 31)起,上述權限被 BLUETOOTH_CONNECT 與 BLUETOOTH_SCAN 取代,且兩者都是執行期危險權限,必須動態向使用者請求;在舊版本上不在此限。

二、控制本機藍牙模組

核心類別是 BluetoothAdapter:

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

// 開啟系統的藍牙啟用設定面板(由使用者確認)
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 0x1);

// 直接開啟藍牙
adapter.enable();

// 關閉藍牙
adapter.disable();

// 開啟本機可發現性(預設 120 秒,最長可延長至 300 秒)
Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);

實務上建議一律用 ACTION_REQUEST_ENABLE 把決定權交給使用者,而不是靜默呼叫 enable();後者在 API 33 起需要 BLUETOOTH_CONNECT 權限,且未經告知就開啟無線電的行為也容易招致使用者反感。另外 getDefaultAdapter() 在 API 31 已 deprecated,替代做法是 BluetoothManager.getDefaultAdapter() 或 getContext().getSystemService(BluetoothManager.class).getAdapter()。

三、搜尋裝置

用 startDiscovery() 啟動搜尋。這是異步方法,呼叫後立刻返回,實際搜尋在系統服務中進行,約持續 12 秒;過程中可用 cancelDiscovery() 中止。

搜尋期間系統會發出三種廣播:

ACTION_DISCOVERY_START:搜尋開始。
ACTION_DISCOVERY_FINISHED:搜尋結束。
ACTION_FOUND:找到裝置,Intent 中帶有 EXTRA_DEVICE(BluetoothDevice)與 EXTRA_CLASS(BluetoothClass)。

// 接收 ACTION_FOUND 的廣播接收器
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // 從 Intent 取出裝置物件
            BluetoothDevice device =
                    intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // 顯示名稱與位址,例如放進 ListView 的 adapter
            mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
        }
    }
};

// 註冊
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
// 別忘了在 onDestroy 中 unregisterReceiver(mReceiver)

四、RFCOMM Socket 通信

兩個裝置要在同一個 RFCOMM channel 上各持有一個 BluetoothSocket,才算建立連線。伺服器端與客戶端取得 Socket 的路徑不同:伺服器端透過 accept() 接受一筆連入,客戶端則主動開啟一條到伺服器的 channel。雙方必須使用相同的 UUID 才能配對成功。

伺服器端

呼叫 listenUsingRfcommWithServiceRecord(String, UUID) 取得 BluetoothServerSocket,再用 accept() 等待連線。注意 accept() 是阻塞方法,必須放在獨立執行緒中;接受連線後通常即可關閉 ServerSocket,因為 RFCOMM 同一 channel 在單一時間點只允許一個連線。

private class AcceptThread extends Thread {
    private final BluetoothServerSocket mmServerSocket;

    public AcceptThread() {
        BluetoothServerSocket tmp = null;
        try {
            // MY_UUID 是這個 App 的 UUID,客戶端必須使用同一組
            tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
        } catch (IOException e) { }
        mmServerSocket = tmp;
    }

    public void run() {
        BluetoothSocket socket = null;
        // 持續等待,直到成功或發生例外
        while (true) {
            try {
                socket = mmServerSocket.accept();
            } catch (IOException e) {
                break;
            }

            if (socket != null) {
                // 在另一條執行緒中處理連線
                manageConnectedSocket(socket);
                try {
                    mmServerSocket.close();
                } catch (IOException e) { }
                break;
            }
        }
    }

    /** 取消監聽,讓執行緒結束 */
    public void cancel() {
        try {
            mmServerSocket.close();
        } catch (IOException e) { }
    }
}

客戶端

先取得目標裝置的 BluetoothDevice,呼叫 createRfcommSocketToServiceRecord(UUID) 取得 Socket,再呼叫 connect()。同樣是阻塞方法,需放在執行緒中。特別注意:連線前一定要先取消搜尋,否則 connect() 會變得非常慢且容易失敗。

private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        BluetoothSocket tmp = null;
        mmDevice = device;
        try {
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) { }
        mmSocket = tmp;
    }

    public void run() {
        // 搜尋會拖慢連線,先取消
        mBluetoothAdapter.cancelDiscovery();

        try {
            mmSocket.connect();   // 阻塞,直到成功或拋出例外
        } catch (IOException connectException) {
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }

        manageConnectedSocket(mmSocket);
    }

    /** 取消進行中的連線並關閉 Socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

連線建立後的資料傳輸

透過 getInputStream() 與 getOutputStream() 取得串流,再用 read() 與 write() 讀寫。read() 會一直阻塞直到有資料;write() 通常不阻塞,但若對端未及時讀取或緩衝區已滿也會暫時停住。

private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }
        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer = new byte[1024];
        int bytes;

        // 持續讀取,直到發生例外
        while (true) {
            try {
                bytes = mmInStream.read(buffer);
                // 交給 UI 執行緒更新畫面
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    /** 由主 Activity 呼叫以送出資料 */
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
    }

    /** 關閉連線 */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

實作上的提醒

藍牙的每個環節幾乎都是阻塞或異步的,務必確認 accept()、connect()、read() 都跑在工作執行緒上,透過 Handler 或 runOnUiThread() 回主執行緒更新 UI。所有 Socket、ServerSocket 與串流都要有明確的關閉路徑,否則裝置配對後會出現無法再連線的僵死狀態。最後記得區分「傳統藍牙(Bluetooth Classic)」與「藍牙低功耗(BLE)」——兩者的 API 幾乎完全不同,本文的 RFCOMM 屬於前者,若要做感測器、穿戴裝置溝通,應該改用 BluetoothGatt 系列。

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