if (mBluetoothSocket != null && !mBluetoothSocket.isConnected()) { Log.d(TAG, "连接已断开"); } else { Log.d(TAG, "连接仍然有效"); }
private void startHeartbeat() { mHeartbeatTimer = new Timer(); mHeartbeatTimer.schedule(new TimerTask() { @Override public void run() { try { if (mBluetoothSocket != null && mBluetoothSocket.isConnected()) { mBluetoothSocket.getOutputStream().write(0); } } catch (IOException e) { e.printStackTrace(); } } }, 0, 1000); //每秒发送一次心跳包 }
mBluetoothSocket.setSoTimeout(3000); //设置超时时间为3秒
注意:以上示例代码仅供参考,实际使用时需要根据具体情况进行修改。