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

Android 開發學習:藍牙 API 使用整理

編輯:關於 Android 程式設計

以下整理 Android 藍牙開發中最常用的幾組 API。

1. 顯式開啟藍牙裝置

跳出一個系統對話框,由使用者確認是否開啟藍牙——這是比較推薦的做法,因為不需要 BLUETOOTH_ADMIN 權限。

Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1);

2. 隱式開啟/關閉藍牙裝置

直接透過程式開關,不會跳出任何提示,因此需要 android.permission.BLUETOOTH_ADMIN 權限。

BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
mAdapter.enable();    // 開啟藍牙裝置
mAdapter.disable();   // 關閉藍牙裝置

3. 取得已配對的裝置

Set<BluetoothDevice> mDevices = mAdapter.getBondedDevices();
if (mDevices.size() > 0) {
    for (BluetoothDevice mDevice : mDevices) {
        mView.append(mDevice.getName() + ":" + mDevice.getAddress() + "\n");
    }
}

4. 搜尋藍牙裝置

搜尋結果是透過廣播回報的,因此要先註冊接收器:

private final BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context mContext, Intent intent) {
        if (BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) {
            BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (mDevice.getBondState() != BluetoothDevice.BOND_BONDED) {
                mView.append(mDevice.getName() + ":" + mDevice.getAddress() + "\n");
            }
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(intent.getAction())) {
            MainActivity.this.setProgressBarIndeterminateVisibility(false);
        }
    }
};

// 監聽找到裝置
IntentFilter mFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(receiver, mFilter);

// 監聽搜尋結束
mFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(receiver, mFilter);

實務上要留意的幾點

權限:基本操作需要 BLUETOOTH,涉及搜尋與設定藍牙狀態則需要 BLUETOOTH_ADMIN;Android 12 以上改為 BLUETOOTH_CONNECT 與 BLUETOOTH_SCAN,且必須執行期動態申請。

搜尋很耗電:discovery 過程會大量消耗電力,建議設定逾時自動停止,並記得在 Activity 銷毀時呼叫 unregisterReceiver() 解除註冊。

建立連線:拿到裝置位址後,真正的資料傳輸需要透過 createRfcommSocketToServiceRecord() 建立 RFCOMM socket,並在子執行緒中處理阻塞式的 connect() 與 read()/write(),避免卡住 UI 線程。

對方名稱可能為 null:getName() 在某些裝置或權限不足時會傳回 null,串接字串前記得判空。

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