简体   繁体   中英

Dialog for incoming bluetooth request

In my application two devices are connected via bluetooth. In the background runs an own thread for the bluetooth connection. (Just like the example ) When one device wants to connect to another device i want a request dialog to be displayed on the second device. So I guess that i have to modify the AcceptThread. The AcceptThread has to inform my mainThread (for example with a Handler).

In the AcceptThread I find this code:

                // This is a blocking call and will only return on a
                // successful connection or an exception
                socket = mmServerSocket.accept();

Now here is my problem: this "blocking call" runs the whole time. How and when shall I inform my mainThread that another device wants to connect?

Definitely afterwards. What you want is the result of the blocking call - of the .accept() . That is socket in your code.

Here is a quote from the Android BluetoothServerSocket documentation:

Then call accept() to listen for incoming connection requests. This call will block until a connection is established, at which point, it will return a BluetoothSocket to manage the connection. Once the BluetoothSocket is acquired, it's a good idea to call close() on the BluetoothServerSocket when it's no longer needed for accepting connections. Closing the BluetoothServerSocket will not close the returned BluetoothSocket.

So don't forget to do:

 mmServerSocket.close()

After you receive a socket correctly - a BluetoothSocket actually -, you can choose what to do with it following the user's choice:

  • Should he go ahead, you just create the AsyncTask that reads from the socket until the AsyncTask is cancelled or an Exception occurs(on Bluetooth disconnect probably).
  • Should he decline, just cancel the socket

If you receive an Exception during the blocking call I would return to the main menu only a toast, saying something failed. But you can do a dialog (like retry?)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM