我正在尝试检查在运行我的应用程序时是否配对了蓝牙设备。
在主要活动中,我找到蓝牙设备并与它们配对。在第二个活动中,我必须检查是否有设备配对。
如果设备已连接,它会开始自动发送数据,但如果没有连接,则它只是显示一个 toast。
我需要在第二个活动开始时执行此操作。我找到了这段代码,但我不知道如何在刚刚创建活动时启动它。
public void onCreate() {
//...
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mReceiver, filter1);
this.registerReceiver(mReceiver, filter2);
}
//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver BTReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
//Do something if connected
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
//Do something if disconnected
}
}
};