kkAyatakaのメモ帳。

誰かの役に立つかもしれない備忘録。

BluetoothSocket

概要

AndroidではそのもズバリのBluetoothSocketクラスが用意されており、コレを使うことでBluetooth通信が簡単にできるようになっている。BluetoothSocketはコンストラクタ経由で生成するのではなく、BluetoothAdapterから順番に取得する必要がある。

  1. BluetoothAdapterの取得とアダプタの確認
  2. ペアリング済みのBluetoothDeviceを取得
  3. BluetoothSocketの取得

機器の検出やペアリング自体もAPI経由で行えるが、今回は事前にOS上でペアリングしてあるものとする。

BluetoothAdapter

BluetoothAdapter adpt = BluetoothAdapter.getDefaultAdapter();

Bluetoothが無ければnullが返る。エミュレーターではBluetoothが使用できないため常にnull。検証には必ず実機が必要になる。

ペアリング済みのBluetoothDevice

Set<BluetoothDevice> devices = adpt.getBondedDevices();

Setで返るので、名前などで判定して必要なデバイスを得る。

BluetoothSocket

UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
socket_ = device.createRfcommSocketToServiceRecord(uuid);
socket_.connect();if (adpt == null) {

Bluetoothプロファイルを示すUUIDを指定してBluetoothSocketを取得する。サーバー側(受けて側)が待ち受けていれば、connectで接続が確立する。

connect成功後は、ソケットのInputStream/OutputStreamで通信を行う。InputStreamはスレッドをブロックするため、別スレッドで実行する。

// 送信
socket_.getOutputStream().write("文字列".getBytes("UTF-8"));

// 受信
handler_ = new Handler();
new Thread() {
    public void run() {
        try {
            while (true) {
                byte[] buf = new byte[1024];
                int len = socket_.getInputStream().read(buf);
                final String str = new String(buf, 0, len, "UTF-8");
                
                handler_.post(new Runnable() {
                    
                    @Override
                    public void run() {
                        // Update GUI
                    }
                });
            }
        }
        catch(IOException e) {
        
        }
    }
}.start();