2011年5月9日月曜日

AndroidでBluetoothのアドレスを取得する

このエントリーをはてなブックマークに追加
Bluetoothを使う際にアドレスを取得しようと思ったのですが,ハマってしまったのでエントリにします.

環境は下記の通りです.
HW:HTC Desire HD
OS: Android 2.2

Androidでは,ローカルのBluetoothデバイスを利用するためにBluetoothAdapter APIが用意されています.

プログラムで実行したいことは,BluetoothAdapterオブジェクトを用いて,Bluetoothを利用可能状態にした後,そのアドレスを取得する,といった動作です.

下記プログラムでは,onCreateメソッド内にて,BluetoothAdapterオブジェクトを生成し,そのisEnabledメソッドにより,BluetoothがON or OFFを判断します.そして,OFFの場合は,Intentを発行後,BluetoothをONにします.
その後,getAddressメソッドを呼び出しアドレスを取得します.

しかし,このgetAddressメソッドの戻り値は"UNKNOWN"となり,ここでエラーが発生します.

この問題を解決し,正しいアドレスを取得するには,onActivityResultメソッドをオーバーライドし,この中で,getAddressメソッドを呼ぶ必要があります.

初めはonCreateメソッド内で全処理を行っていたのですが,BluetoothをONにするのを待つことなく,getAddressメソッドが呼び出されたことが原因かと思います.

そこで,RESULTを返すようにし,BluetoothをONにした後に呼び出されるonActivityResultメソッド内で処理を行います.

※このプログラムではBluetoothをOFFにできないので,試した後は手動でOFFにしてください.
package jp.ayakix;

import android.app.Activity;
import android.bluetooth.*;
import android.os.Bundle;
import android.util.Log;
import android.content.Intent;

public class BluetoothTest extends Activity {
private static final int REQUEST_ENABLE_BT = 3;
private BluetoothAdapter bAdapter;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

bAdapter = BluetoothAdapter.getDefaultAdapter();

// デバイスがBluetoothを備えているか?
if (bAdapter == null) {
Log.d("MYTAG", "Device does not support Bluetooth");
} else {
// Bluetoothが利用可能状態か?
if (!bAdapter.isEnabled()) {
// 利用可能状態でない場合=>利用可能にする
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

// アドレスを取得できない
Log.d("MYTAG", bAdapter.getName());
Log.d("MYTAG", bAdapter.getAddress());
}
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == RESULT_OK) {
Log.d("MYTAG", "Device can use Bluetooth");
// アドレスを取得できる
Log.d("MYTAG", bAdapter.getName());
Log.d("MYTAG", bAdapter.getAddress());
} else if (resultCode == RESULT_CANCELED) {
Log.d("MYTAG", "Device cannot use Bluetooth");
}
}
}
}