我没有使用过平板电脑,但我写过一个应用程序,用于Android手机使用SPP。我发现为了使蓝牙稳定,我必须手动绑定我想要通信的设备。我们在应用程序中使用下面的代码来启动绑定过程,它应该会像你通过设置菜单手动配对设备一样保留绑定信息。
以下是一般流程:
1)注册BroadcastReceiver以侦听BluetoothDevice.ACTION_BOND_STATE_CHANGED
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;
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)
{
if (bondState == BluetoothDevice.BOND_BONDED || bondState == BluetoothDevice.BOND_NONE)
{
}
}
}
}
}
5) 打开套接字并进行通信
您还可以通过反射使用“removeBond”方法将设备从配对列表中删除。
希望这可以帮助你!