デスクトップアプリケーション(Javaで記述)からAndroidアプリケーションにBluetooth経由で接続しようとしています。
デスクトップアプリケーションには、BlueCoveAPIを使用しています。
サーバー(デスクトップアプリケーション)を起動してAndroidアプリケーションを起動すると、接続は正常に機能します。(つまり、クライアントは「Hello World」を送信し、サーバーはそれをコンソールに出力します)。しかし、アプリケーションを終了して([戻る]または[ホーム]ボタンを押して)アプリケーションに戻ると、ソケット接続が失われているようです。
Bluetoothソケットがすでに接続されているかどうかを確認するにはどうすればよいですか?
ソケットの接続を確認して、再度接続しないようにします。
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();
}
}
};