Androidプログラマへの道 〜 Moonlight 明日香 〜 - Bluetoothデバイスの情報を取得する
Bluetoothデバイスの各種情報を取得するには, BluetoothDeviceクラスを利用する.



デバイスの各種情報取得

周辺のBluetoothデバイスのスキャンを例に, 発見したデバイスの各種情報を表示する.
  • Bluetooth01.java
    • 他のBluetoothデバイスのスキャンについては, Bluetoothデバイスを探すを参照.
    • Intent#getParcelableExtraメソッドで, BluetoothDeviceオブジェクトを取得する.
    • BluetoothDevie#getXXXメソッドで, 各種情報を取得する.
メソッド情報API Level
getAddress()MACアドレス5
getBluetoothClass()デバイスクラス5
getBondState()接続状態5
getName()デバイス名5
getUuids()UUID15
package com.moonlight_aska.android.bluetooth01;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.TextView;

public class Bluetooth01 extends Activity {
  private BluetoothAdapter mBtAdapter;
  private TextView mScanResult;
  private String mResult = "";
  private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      if (BluetoothDevice.ACTION_FOUND.equals(action)) {
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        mResult += "Name : " + device.getName() + "\n";
        mResult += "Device Class : " + device.getBluetoothClass().getDeviceClass() + "\n";
        mResult += "MAC Address : " + device.getAddress() + "\n";
        mResult += "State : " + getBondState(device.getBondState()) + "\n";
        mScanResult.setText(mResult);
      }
    }
  };

  String getBondState(int state) {
    String strState;

    switch (state) {
    case BluetoothDevice.BOND_BONDED:
      strState = "接続履歴あり";
      break;
    case BluetoothDevice.BOND_BONDING:
      strState = "接続中";
      break;
    case BluetoothDevice.BOND_NONE:
      strState = "接続履歴なし";
      break;
    default :
      strState = "エラー";
    }
    return strState;
  }

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mScanResult = (TextView)findViewById(R.id.bt_text);
    // インテントフィルタの作成
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    // ブロードキャストレシーバの登録
    registerReceiver(mReceiver, filter);

    // BluetoothAdapterのインスタンス取得
    mBtAdapter = BluetoothAdapter.getDefaultAdapter();
    // Bluetooth有効
    if (!mBtAdapter.isEnabled()) {
      mBtAdapter.enable();
    }
    // 周辺デバイスの検索開始
    mBtAdapter.startDiscovery();
  }

  @Override
  protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    // 検索中止
    if (mBtAdapter.isDiscovering()) {
      mBtAdapter.cancelDiscovery();
    }
    unregisterReceiver(mReceiver);
  }
}