I am trying to create an app that allows a string to be sent from one Android phone to another. The code for this is provided below. However, it isn\'t working as I keep get
TWO MAJOR PROBLEMS-
1) connect()
is a blocking call, you should always perform this connection procedure in a thread that is separate from the main activity (UI) thread. You are doing this on the main thread.
Note: You should always call cancelDiscovery() to ensure that the device is not performing device discovery before you call connect(). If discovery is in progress, then the connection attempt is significantly slowed, and it's more likely to fail.
2) If you are using the same code on the second device too(so that you could send or receive data) then I don't see any call to accept()
. accept()
listens for connection requests.
Again, accept()
call is a blocking call, it should not be executed in the main activity UI thread so that your application can still respond to other user interactions.
Simplified thread for the server component that accepts incoming connections:
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket
// because mmServerSocket is final.
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code.
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) {
Log.e(TAG, "Socket's listen() method failed", e);
}
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned.
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
Log.e(TAG, "Socket's accept() method failed", e);
break;
}
if (socket != null) {
// A connection was accepted. Perform work associated with
// the connection in a separate thread.
manageMyConnectedSocket(socket);
mmServerSocket.close();
break;
}
}
}
// Closes the connect socket and causes the thread to finish.
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close the connect socket", e);
}
}
}
Android documentation - BLUETOOTH