私はアンドロイドが初めてで、ブルートゥース機能を備えたアプリケーションを作成しています。Bluetooth アダプターを設定して自分のデバイス情報を取得することはできますが、startdiscovery を使用して Bluetooth デバイスを検出することはできませんでした。スキャンを開始しても何もしません。
onclicklistner を使用してスキャンを開始しています。
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!(bluetooth.isEnabled())) {
status = "Bluetooth is not Enabled.";
Toast.makeText(AddUser.this, status, Toast.LENGTH_LONG).show();
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
else
{
scand();
}
}
これは、「public void onCreate」関数の直後に配置した onActivityResult 関数です。
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
System.out.println(resultCode);
if (resultCode == RESULT_CANCELED) {
status="Error Enabling bluetooth";
Toast.makeText(AddUser.this, status, Toast.LENGTH_LONG).show();
} else {
scand();
}
}
これは私のscand関数で、startdiscoveryを呼び出しています:
private void scand()
{
bluetooth.startDiscovery();
Log.d("itmes", ""+items.size());
item1 = new String[items.size()];
item1 = items.toArray(item1);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose a device");
builder.setItems(item1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), item1[item], Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
}
これはブロードキャストレシーバーです:
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
Log.e("br", "--- device found ---");
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
items.add(device.getName());
}
}
};
上記の BroadcastReceiver のコードでは、見つかったデバイス名を文字列 ArrayList "items" に入れようとしています。
次のように、oncreate 関数内にブロードキャストレシーバーを登録しています。
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
androidmanifest ファイルで Bluetooth パーミッションを設定しました。上記の scand 関数では、検出されたデバイスのリストを表示することになっていますが、タイトルだけの空のダイアログが表示されています。startdiscoveryとbroadcastreceiverをうまく使って結果をアラートダイアログに表示する方法を教えてください。