web-dev-qa-db-ja.com

ペアリングされたBluetoothデバイスをAndroidでプログラムでペアリング解除または削除するにはどうすればよいですか?

このプロジェクトでは、Android携帯電話を使用してarduinoデバイスに接続します。しかし、ペアリングされたデバイスのペアリングを解除するにはどうすればよいですか。

PS:最初に、ペアリングされたデバイスを長押しするとペアリングが解除されることを知っています。
しかし、ここでの質問は、プログラムでこれをどのように実現するかです。

2番目に、bluetoothdeviceとbluetoothAdapterクラスをチェックしましたが、これを実装する機能はありません。

ありがとう。

34
Dev Perfecular

このコードは私のために機能します。

private void pairDevice(BluetoothDevice device) {
    try {
        if (D)
            Log.d(TAG, "Start Pairing...");

        waitingForBonding = true;

        Method m = device.getClass()
            .getMethod("createBond", (Class[]) null);
        m.invoke(device, (Object[]) null);

        if (D)
            Log.d(TAG, "Pairing finished.");
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    }
}

private void unpairDevice(BluetoothDevice device) {
    try {
        Method m = device.getClass()
            .getMethod("removeBond", (Class[]) null);
        m.invoke(device, (Object[]) null);
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    }
}
59
Dev Perfecular

すべてのデバイスのペアリングを解除します。

Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                try {
                    Method m = device.getClass()
                            .getMethod("removeBond", (Class[]) null);
                    m.invoke(device, (Object[]) null);
                } catch (Exception e) {
                    Log.e("Removing has been failed.", e.getMessage());
                }
            }
        }
12
Péter Hidvégi

bluetoothServiceクラスには、ペアリングされたデバイスのペアリングを解除するremovebond()メソッドがあります。最後に、このメソッドはrmovebondnative()を呼び出します。

1
chandan kumar

Kotlinを使用している場合:

fun removeBond(device: BluetoothDevice) {
    try {
        device::class.Java.getMethod("removeBond").invoke(device)
    } catch (e: Exception) {
        Log.e(TAG, "Removing bond has been failed. ${e.message}")
    }
}
0
Exaqt