0
0

【Android/Java】Bluetoothペアリング機器の削除(任意のもの以外)

Posted at

やりたいこと

製品に付随しているBluetooth機器(例えば、AndroidTVに付随しているBluetoothリモコン)以外のペアリング機器を削除したい。
ネットカフェのPCなど、不特定多数の使用が想定される状況で、利用者がペアリングした機器を、利用終了後に削除したいのが目的での調査メモ

Step1.実装方法

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // 削除しない機器のデバイスIDを指定
    final String excludeDevices = "0x1111";

    // 端末起動直後は、Bluetooth OFFの場合があるため、ONになるまでまつ
    do {
        BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
        if (null != ba) {
            // Bluethooth設定有効時のみ
            if (ba.isEnabled()) {
                Set<BluetoothDevice> bd = ba.getBondedDevices();
                for (BluetoothDevice device : bd) {
                    if (excludeDevices != device.getBluetoothClass().getDeviceClass()) {
                        // ペアリングを解除
                        Method method = device.getClass().getMethod("removeBond");
                        method.invoke(device);
                    }
                }
                break;
            }
        }
        Thread.sleep(1000);
    } while (true);
}

解説

  1. do-while(true)で無限ループし、BluetoothがONになるのを待ち続ける…永遠にONとならなかった場合の考慮は別途する必要がある
  2. device.getBluetoothClass().getDeviceClass()で、ペアリングしているBluetooth機器情報を取得し、削除対象外かを判断
  3. method.invoke(device)でBluetoothのペアリングを解除

最後に

ハードよりの開発をすることが増えてきて、こういった変な実装ばかりしている気がする。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0