私はタブレットで作業したことはありませんが、Android フォン用の SPP を使用するアプリを作成しました。私が見つけたのは、Bluetooth を安定させるには、通信したいデバイスと手動で結合する必要があるということでした。以下のコードを使用して、アプリ内からボンディングを開始しました。設定メニューから手動でペアリングした場合と同様に、ボンディングが保持されます。
一般的なフローは次のとおりです。 1) BluetoothDevice.ACTION_BOND_STATE_CHANGED をリッスンする BroadcastReceiver を登録し
ます。 2) デバイスの検出後、BluetoothDevice オブジェクトが必要です。
3) リフレクションを使用して BluetoothDeviceObject の「createBond」メソッドを呼び出します
3a) ソケットを開く前に結合状態変更イベントを待ちます
BluetoothDevice device = {obtained from device discovery};
Method m = device.getClass().getMethod("createBond", (Class[])null);
m.invoke(device, (Object[])null);
int bondState = device.getBondState();
if (bondState == BluetoothDevice.BOND_NONE || bondState == BluetoothDevice.BOND_BONDING)
{
waitingForBonding = true; // Class variable used later in the broadcast receiver
// Also...I have the whole bluetooth session running on a thread. This was a key point for me. If the bond state is not BOND_BONDED, I wait here. Then see the snippets below
synchronized(this)
{
wait();
}
}
4) 結合状態が BOND_BONDING から BOND_BONDED に変わるのを待ちます。
BroadcastReceiver の内部:
public void onReceive(Context context, Intent intent)
{
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(intent.getAction()))
{
int prevBondState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, -1);
int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
if (waitingForBonding)
{
if (prevBondState == BluetoothDevice.BOND_BONDING)
{
// check for both BONDED and NONE here because in some error cases the bonding fails and we need to fail gracefully.
if (bondState == BluetoothDevice.BOND_BONDED || bondState == BluetoothDevice.BOND_NONE)
{
// safely notify your thread to continue
}
}
}
}
}
5) ソケットを開いて通信する
リフレクションを介して「removeBond」メソッドを使用して、デバイスをペアリング リストから削除することもできます。
お役に立てれば!