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

Android 藍牙實作:跳過配對框的自動配對

編輯:關於 Android 程式設計

在開發藍牙相關應用時,最惱人的往往不是連線本身,而是每次配對都要跳出系統的「配對確認框」與 PIN 輸入。本文示範如何透過反射呼叫 Android 隱藏的 API,把手機與藍牙裝置(例如藍牙採集器)的自動配對流程走完,省去人工點擊的麻煩。

思路:為什麼要動用反射

網路上常見的做法是攔截配對廣播再設定 PIN,但多數市售手機並不支援 android.bluetooth.device.action.PAIRING_REQUEST 這個常數,導致流程卡住。真正的關鍵在於能否「進入」配對請求的回應環節。這時我們需要借助 BluetoothDevice 那些未公開的方法——而呼叫它們最直接的方式就是反射。

封裝配對工具類 ClsUtils

以下這個工具類幾乎可以原封不動地重複使用,把 createBond、setPin、取消使用者輸入等動作都包成靜態方法:

package zicox.esc;

import java.lang.reflect.Method;
import android.bluetooth.BluetoothDevice;
import android.util.Log;

public class ClsUtils {

    // 與設備配對(對應 Settings 原始碼中的 createBond)
    static public boolean createBond(Class btClass, BluetoothDevice btDevice)
            throws Exception {
        Method m = btClass.getMethod("createBond");
        Boolean r = (Boolean) m.invoke(btDevice);
        return r.booleanValue();
    }

    // 與設備解除配對
    static public boolean removeBond(Class btClass, BluetoothDevice btDevice)
            throws Exception {
        Method m = btClass.getMethod("removeBond");
        Boolean r = (Boolean) m.invoke(btDevice);
        return r.booleanValue();
    }

    // 設定 PIN
    static public boolean setPin(Class btClass, BluetoothDevice btDevice, String str)
            throws Exception {
        try {
            Method m = btClass.getDeclaredMethod("setPin", new Class[]{byte[].class});
            Boolean r = (Boolean) m.invoke(btDevice, new Object[]{str.getBytes()});
            Log.e("returnValue", "" + r);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    // 取消使用者輸入(跳過配對確認框)
    static public boolean cancelPairingUserInput(Class btClass, BluetoothDevice device)
            throws Exception {
        Method m = btClass.getMethod("cancelPairingUserInput");
        Boolean r = (Boolean) m.invoke(device);
        return r.booleanValue();
    }

    // 取消整個配對流程
    static public boolean cancelBondProcess(Class btClass, BluetoothDevice device)
            throws Exception {
        Method m = btClass.getMethod("cancelBondProcess");
        Boolean r = (Boolean) m.invoke(device);
        return r.booleanValue();
    }

    // 一站式配對:檢查狀態後設定 PIN 並建立 bond
    static public boolean pair(String strAddr, String strPsw) {
        boolean result = false;
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        adapter.cancelDiscovery();
        if (!adapter.isEnabled()) adapter.enable();
        if (!BluetoothAdapter.checkBluetoothAddress(strAddr)) {
            Log.d("mylog", "devAdd un effective!");
        }
        BluetoothDevice device = adapter.getRemoteDevice(strAddr);
        if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
            try {
                setPin(device.getClass(), device, strPsw);
                createBond(device.getClass(), device);
                result = true;
            } catch (Exception e) {
                Log.d("mylog", "setPin failed!");
                e.printStackTrace();
            }
        } else {
            try {
                createBond(device.getClass(), device);
                setPin(device.getClass(), device, strPsw);
                createBond(device.getClass(), device);
                result = true;
            } catch (Exception e) {
                Log.d("mylog", "setPin failed!");
                e.printStackTrace();
            }
        }
        return result;
    }
}

在 Activity 中攔截廣播並自動配對

有了工具類,接下來只要在 Activity 註冊廣播接收器,監聽「找到裝置」、「配對狀態改變」以及「配對請求」等事件。當配對請求送達時,我們就反射呼叫 setPin → createBond → cancelPairingUserInput,讓系統不再跳出確認框:

if (BluetoothDevice.ACTION_FOUND.equals(action)) {
    device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    if (device.getBondState() == BluetoothDevice.BOND_NONE) {
        try {
            ClsUtils.setPin(device.getClass(), device, "0000");
            ClsUtils.cancelPairingUserInput(device.getClass(), device);
        } catch (Exception e) { e.printStackTrace(); }
    }
} else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
    device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    switch (device.getBondState()) {
        case BluetoothDevice.BOND_BONDING:
            Log.d("BlueToothTestActivity", "正在配對......"); break;
        case BluetoothDevice.BOND_BONDED:
            Log.d("BlueToothTestActivity", "完成配對");
            connect(device);   // 配對成功後建立連線
            break;
        case BluetoothDevice.BOND_NONE:
            Log.d("BlueToothTestActivity", "取消配對"); break;
    }
}

配對成功後建立 RFCOMM 連線

一旦 BOND_BONDED 抵達,就能用 SPP 通訊協定的標準 UUID 建立 socket 並連線,之後即可開始資料收發:

private void connect(BluetoothDevice btDev) {
    final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    try {
        btSocket = btDev.createRfcommSocketToServiceRecord(SPP_UUID);
        btSocket.connect();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

別忘了在 onDestroy() 中註銷廣播接收器(unregisterReceiver),並關閉 socket,避免資源外洩。透過這套反射搭配廣播監聽的組合,就能在多數裝置上實作出無需人工介入的自動配對流程。

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