蓝牙接收器在Android中不工作

蓝牙接收器在Android中不工作,android,bluetooth,Android,Bluetooth,我正在Android应用程序中工作,从硬件蓝牙设备接收蓝牙数据。我已经看到了stack的所有帖子,还使用示例应用程序设计了我的代码。 问题是,我的“蓝牙接收器”不工作,每当我从硬件设备发送数据时,它第一次工作,但恰恰是第二次,它总是无法接收数据通知 public class BluetoothDataReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent inten

我正在Android应用程序中工作,从硬件蓝牙设备接收蓝牙数据。我已经看到了stack的所有帖子,还使用示例应用程序设计了我的代码。 问题是,我的“蓝牙接收器”不工作,每当我从硬件设备发送数据时,它第一次工作,但恰恰是第二次,它总是无法接收数据通知

public class BluetoothDataReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

ConfigClass.bluetoothDataReceive++;
if (ConfigClass.bluetoothDataReceive == 1) {
ConfigClass.showToast(context,
ConfigClass.MSG_RECEIVE_BLUETOOTH_DATA);

}else if (ConfigClass.bluetoothDataReceive ==2) {
ConfigClass.bluetoothDataReceive = 0;

}
}
}

请帮我解决…我一直在努力解决这个问题。

BroadcastReceiver.onReceive()在不同于您的UI的线程中运行。UI不是线程安全的。在其中执行Toast()是个坏主意,可能会导致意外的结果…

BroadcastReceiver对象仅在调用onReceive(上下文、意图)期间有效。一旦代码从此函数返回,系统将认为对象已完成且不再处于活动状态。那么解决方案是什么?您需要使用StickyBroadcastIntent。它围绕着你的服务。检查这个,我用了这个粘胶,但是遇到了同样的问题。IntentFilter actionChanged=新的IntentFilter(BluetoothAdapter.ACTION\u STATE\u CHANGED);Intent=this.registerReceiver(null,actionChanged);我需要定期接收数据。