【发布时间】:2018-08-29 08:53:16
【问题描述】:
我如何在 android 中制作一个可以在 android 设备和蓝牙扬声器之间提供连接的应用程序。
【问题讨论】:
-
您可能需要自己进行研究,如果遇到任何问题,请发布问题
标签: android bluetooth android-bluetooth
我如何在 android 中制作一个可以在 android 设备和蓝牙扬声器之间提供连接的应用程序。
【问题讨论】:
标签: android bluetooth android-bluetooth
如何配对:
private void pairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
如何取消配对:
private void unpairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
接收器捕捉配对过程:
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
showToast("Paired");
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
showToast("Unpaired");
}
}
}
};
注册接收者:
IntentFilter intent = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mPairReceiver, intent);
【讨论】: