自動ペアリング

Bluetooth携帯プリンタに印字しようとしたら、どうもAndroidではBluetooth機器をペアリングしないとRFCOMMやSPPでは接続できないみたい。

一応、BluetoothDevice.javaを見てみるとcreateRfcommSocketメソッドでのBluetoothSocketクラス生成時にauthフラグが固定でtrueになっているから、これがfalseで設定できればあるいはと思ったけど・・・

FHTPR231ではペアリングがそもそもできないようなので、BLM80で印字してみた。結果印字できた。

ただ、毎回ペアリングを手動で行うのはめんどうなので自動でペアリングする方法

// 自動ペアリング処理
protected boolean execPairing(String bluetoothAddress, String pinCode) throws Exception {

    // Bluetoothアダプタ取得
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

    // BluetoothデバイスをMACアドレスから取得
    BluetoothDevice device = adapter.getRemoteDevice(bluetoothAddress);

    // ペアリング開始処理呼び出し
    Method createBond = device.getClass().getMethod("createBond", new Class[] {});
    Boolean result = (Boolean)createBond.invoke(device);
    if (!result.booleanValue()) {
        return false;
    }

    // PINコードをUTF8に変換
    Method convertPinToBytes = BluetoothDevice.class.getMethod("convertPinToBytes", new Class[] { String.class });
    byte[] pinCodes = (byte[])convertPinToBytes.invoke(BluetoothDevice.class, pinCode);

    // PINコード登録
    Method setPin = device.getClass().getMethod("setPin", new Class[] { byte[].class });
    result = (Boolean)setPin.invoke(device, pinCodes);
    if (!result.booleanValue()) {
        return false;
    }

    return true;
}

本当はこの後にBroadcastReceiverでACTION_BOND_STATE_CHANGEDをキャッチする処理が
いると思うけど・・・

しかし、なんかリフレクションでしか呼べないメソッドばっかりだなぁ。