我正在尝试通过蓝牙从桌面应用程序(用 Java 编写)连接到 Android 应用程序。
对于桌面应用程序,我使用的是BlueCove API。
当我启动服务器(桌面应用程序)并启动 Android 应用程序时,连接工作正常。(即客户端发送“Hello World”,服务器在控制台中打印)。但是当我离开应用程序(通过按返回或主页按钮)并返回它时,套接字连接似乎丢失了。
如何检查蓝牙插座是否已连接?
我想检查套接字的连接是否再次连接。
我应该在onPause
,onResume
方法中写什么(如果是的话)?
我想在onDestroy
方法中我应该关闭套接字。
我也尝试使用IntentFilter
检查连接状态,但它没有用。
@Override
public void onCreate(Bundle savedInstanceState) {
// .....
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mReceiver, filter1);
this.registerReceiver(mReceiver, filter2);
this.registerReceiver(mReceiver, filter3);
}
//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//Device found
Toast.makeText(BluetoothClient.this, "Device not found", 2).show();
}
else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
//Device is now connected
Toast.makeText(BluetoothClient.this, "Device connected", 2).show();
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//Done searching
Toast.makeText(BluetoothClient.this, "Done searching", 2).show();
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
//Device is about to disconnect
Toast.makeText(BluetoothClient.this, "Device about to connect", 2).show();
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
//Device has disconnected
Toast.makeText(BluetoothClient.this, "Device disconnected", 2).show();
}
}
};