Java 蓝牙已连接但未发送数据
我正在做一个项目,将我的Android手机连接到Arduino蓝牙收发器。它工作正常,直到手机进入暂停(睡眠?)模式;当这种情况发生时,我建立的蓝牙连接似乎仍然存在,但没有数据传输。我使用的是Android Sdk 30 我做的是:我有一个包含BT设备的UI列表供用户选择;选择一个后,将调用该选项以连接:Java 蓝牙已连接但未发送数据,java,android,bluetooth,Java,Android,Bluetooth,我正在做一个项目,将我的Android手机连接到Arduino蓝牙收发器。它工作正常,直到手机进入暂停(睡眠?)模式;当这种情况发生时,我建立的蓝牙连接似乎仍然存在,但没有数据传输。我使用的是Android Sdk 30 我做的是:我有一个包含BT设备的UI列表供用户选择;选择一个后,将调用该选项以连接: // in my BluetoothService class private BluetoothDevice bluetoothDevice; private BluetoothSocket
// in my BluetoothService class
private BluetoothDevice bluetoothDevice;
private BluetoothSocket bluetoothSocket;
public void connect(BluetoothDevice device) {
try {
bluetoothDevice = device;
String uuid = getString(R.string.bluetooth_uuid);
bluetoothSocket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(UUID.fromString(uuid));
bluetoothSocket.connect();
if (bluetoothSocket.isConnected()) {
Log.i(TAG, "connected to " + device + " with socket " + bluetoothSocket);
} else {
Log.w(TAG, "still not connected to " + device + " with socket " + bluetoothSocket);
}
} catch (IOException e) {
Log.e(TAG, "failed to connect to device", e);
}
}
同样,这很好;建立连接并发送/接收数据
private ScheduledFuture<?> sendScheduler; // canceled in onDestroy()
public void onCreate() {
sendScheduler = Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
sendData(lastLevelSent); // i can post sendData, but it works in normal state
}, 30, 30, TimeUnit.SECONDS);
}
现在,我每30秒发送一次数据,并在接收器侧点亮一个led,直到60秒后没有收到数据
private ScheduledFuture<?> sendScheduler; // canceled in onDestroy()
public void onCreate() {
sendScheduler = Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
sendData(lastLevelSent); // i can post sendData, but it works in normal state
}, 30, 30, TimeUnit.SECONDS);
}
private ScheduledFuture sendScheduler;//在onDestroy()中取消
public void onCreate(){
sendScheduler=Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(()->{
sendData(lastLevelSent);//我可以发布sendData,但它在正常状态下工作
},30,30,时间单位为秒);
}
现在,当手机进入睡眠状态(即我按下电源按钮一次)时,led在60秒后熄灭,即没有收到任何数据。然而,连接本身似乎仍在建立(我可以通过接收器led闪烁的方式来判断)
当我唤醒设备时,它不会继续发送数据。我的应用程序中的“断开连接”按钮不起作用(bluetoothSocket.close()
),再次尝试连接到设备也不起作用。我必须关闭应用程序,然后才能断开连接
我正在使用的连接是否仍然有效的检查是bluetoothSocket!=null&&bluetoothSocket.isConnected()
我确实将我的应用程序添加到了Android设置中的“不要进入待机状态”
那么,我如何说服应用程序在睡眠模式下继续发送数据,或者至少可靠地检查连接状态