C/C++プログラマの管理者が, Androidプログラムにチャレンジ. AndroidプログラミングのTipsをメモっていく予定です.

接続履歴のある(過去にペアリング済み)Bluetoothデバイスのリストを取得するには, BluetoothAdapterクラスを利用する.



デバイスリストの取得

  • Bluetooth03.java
    • BluetoothAdapter#getDefaultAdapterメソッドで, BluetoothAdapterのインスタンスを取得する.
    • BluetoothAdapter#getBondedDevicesメソッドで, 過去にペアリング履歴のあるデバイスリストを取得する.
package com.moonlight_aska.android.bluetooth03;

import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.widget.TextView;

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

    TextView btText = (TextView)findViewById(R.id.bt_text);
    BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
    // ペアリング済みのデバイス一覧を取得
    Set<BluetoothDevice> btDevices = btAdapter.getBondedDevices();
    String devList = "";
    for (BluetoothDevice device : btDevices) {
      devList += "Device : " + device.getName() + "(" + getBondState(device.getBondState()) + ")\n";
    }
    btText.setText(devList);
  }

  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;
  }
}
  • AndroidManifest.xml
    • Bluetoot設定の操作を行うには, "android.permission.BLUETOOTH"パーミションを設定する.
?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.moonlight_aska.android.bluetooth03"
  android:versionCode="1"
  android:versionName="1.0" >
  <uses-sdk android:minSdkVersion="8" />
  <uses-permission android:name="android.permission.BLUETOOTH"/>

  <application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
      android:name=".Bluetooth03"
      android:label="@string/app_name" >
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
  </application>
</manifest>



コメントをかく


「http://」を含む投稿は禁止されています。

利用規約をご確認のうえご記入下さい

Menu


逆引き(基礎編)

画面表示/操作(49)

フラグメント(1)

逆引き(応用編)

Firebase(2)

AD



管理人/副管理人のみ編集できます