2

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

Bluetoothソケットがすでに接続されているかどうかを確認するにはどうすればよいですか?
ソケットの接続を確認して、再度接続しないようにします。

onPauseonResumeメソッドに何を書くべきですか(その場合) ?
この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();
        }           
    }
};
4

1 に答える 1

6

サーバー
クライアント

2つのソースコードファイルを変更しました。
これで正常に動作するはずです。モバイルアプリに入る前にBTが開かれない場合(しばらくの間スタックしすぎる)に関するいくつかの小さなバグがあります。このクライアント/サーバーを使用したい場合は、onPause(), onResume(), onDestroy()機能を確認する必要があります。

問題は、ソケットを正しく使用しなかったことです。

このようなアプリケーションをBTで実装したい方のお役に立てば幸いです。

于 2011-05-24T15:25:47.143 に答える