I'm trying to make an app that communicates with nearby devices.
My app is composed of the main activity that asks to enable bluetooth and sets the discoverable mode, so it waits for a connection to be made.
The second activity takes care of finding nearby devices and making the pairing.
After pairing pairing some configuration messages are exchanged and then both start a ThirdActivity that deals with the communication between the two devices.
I can successfully exchange these messages but the problem is that I need to pass the BluetoothService object (which keeps the communication information) to the Third Activity.
Since I don't think I can implement parcelable then I simply closed the connection without eliminating the pairing and then recreate AcceptThread and ConnectThread in the thirdActivity by creating a new BluetoothService object but always passing the same BluetoothDevice.
From the various logs what happens is that the AcceptThread waits on the accept(), while the ConnectThread fails the connect() reporting this error.
W/System.err: java.io.IOException: read failed, socket might closed or timeout, read ret: -1
at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:762)
at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:776)
at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:399)
at com.crossthebox.progetto.BluetoothService$ConnectThread.run(BluetoothService.java:118)
What can I do?
This is the BluetoothService Class
public class BluetoothService {
private UUID myid = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final String appName = "myapp";
private static final int STATE_NONE = 0; // we're doing nothing
private static final int STATE_LISTEN = 1; // now listening for incoming connections
private static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
private static final int STATE_CONNECTED = 3;
private static final int STATE_BUFFER_NOT_EMPTY = 4;
private String message ="";
private int mState;
private final BluetoothAdapter mBluetoothAdapter;
Context mContext;
private AcceptThread mAcceptThread;
private ConnectThread mConnectThread;
private BluetoothDevice mDevice;
private UUID deviceUUID;
private ConnectedThread mConnectedThread;
public BluetoothService(Context context) {
mContext = context;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mState = STATE_NONE;
}
private class AcceptThread extends Thread {
private final BluetoothServerSocket bluetoothServerSocket;
public AcceptThread(){
BluetoothServerSocket tmp = null;
try{
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(appName, myid);
}catch (IOException e){
}
bluetoothServerSocket = tmp;
mState = STATE_LISTEN;
}
public void run() {
BluetoothSocket socket = null;
try {
socket = bluetoothServerSocket.accept();
} catch (IOException e) {
}
if (socket != null) {
mState = STATE_CONNECTING;
connected(socket);
}
}
public void cancel() {
try {
bluetoothServerSocket.close();
} catch (IOException e) {
}
}
}
private class ConnectThread extends Thread {
private BluetoothSocket mSocket;
public ConnectThread(BluetoothDevice device, UUID uuid) {
mDevice = device;
deviceUUID = uuid;
}
public void run(){
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = mDevice.createRfcommSocketToServiceRecord(deviceUUID);
} catch (IOException e) {
}
mSocket = tmp;
mBluetoothAdapter.cancelDiscovery();
try {
mSocket.connect(); //this throws exception for socket close ( but only the second time)
} catch (IOException e) {
// Close the socket
try {
mSocket.close();
} catch (IOException e1) {
}
e.printStackTrace();
}
connected(mSocket);
}
public void cancel() {
try {
mSocket.close();
} catch (IOException e) {
}
}
}
public synchronized void start() {
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if (mAcceptThread == null) {
mAcceptThread = new AcceptThread();
mAcceptThread.start();
}
}
public void startClient(BluetoothDevice device,UUID uuid){
mConnectThread = new ConnectThread(device, uuid);
mConnectThread.start();
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mSocket;
private final InputStream mInStream;
private final OutputStream mOutStream;
public ConnectedThread(BluetoothSocket socket) {
mSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = mSocket.getInputStream();
tmpOut = mSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mInStream = tmpIn;
mOutStream = tmpOut;
}
public void run(){
byte[] buffer = new byte[1024];
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
// Read from the InputStream
try {
bytes = mInStream.read(buffer);
if(bytes != 0) {
String incomingMessage = new String(buffer, 0, bytes);
message = incomingMessage;
System.out.println("HO LETTO " + message);
mState = STATE_BUFFER_NOT_EMPTY;
}
} catch (IOException e) {
break;
}
}
}
//Call this from the main activity to send data to the remote device
public void write(byte[] bytes) {
try {
mOutStream.write(bytes);
} catch (IOException e) {
}
}
//termina la connessione
public void cancel() {
try {
mSocket.close();
} catch (IOException e) { }
}
}
private void connected(BluetoothSocket mSocket) {
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(mSocket);
mConnectedThread.start();
mState = STATE_CONNECTED;
}
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (mState != STATE_CONNECTED) {
return;}
r = mConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
}
public int getState(){
return mState;
}
public String getMessage(){
String tmp = null;
if(!message.equals("")){
tmp = message;
message = "";
}
mState = STATE_CONNECTED;
return tmp;
}
public void setState(int state){
this.mState = state;
}
public void cancel(){
if(mAcceptThread != null) {
mAcceptThread.cancel();
mAcceptThread = null;
}
if(mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if(mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transition);
/* * */
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
/* * */
if(requestCode == DISCOVER_REQUEST){
if(resultCode == 120){
bluetoothService = new BluetoothService(this);
bluetoothService.start();
//after receiving some message correctly
Intent thirdActivity = new Intent(this, com.project.ThirdActivity.class);
bluetoothService.cancel();
this.startActivity(thirdActivity);
finish();
}
if(resultCode == RESULT_CANCELED){
finish();
}
}
}
}
SecondActivity the way I cancel the connection is pretty the same as MainActivity. I close the socket after some message and then start ThirdActivity
ThirdActivity
if(mode == CLIENT){
BluetoothDEvice bluetoothDevice = getIntent().getExtras().getParcelable("btdevice");
bluetoothService.startClient(bluetoothDevice,myid);
}else //SERVER
bluetoothService.start();
Possible solution:
Pass the selected MAC address from Activity2 to Activity3
In Activity3 Start the ConnectThread in the Bluetooth Service.
Use a Handler to communicate between service and the Activity3.
Make sure you close the Thread when sockets disconnect.
A brilliant example is in the following link:
https://github.com/googlesamples/android-BluetoothChat
I have the following implementation of ToyVpnService which I got frome here
public class ToyVpnService extends VpnService implements Handler.Callback, Runnable {
private static final String TAG = "ToyVpnService";
private Handler mHandler;
private Thread mThread;
private ParcelFileDescriptor mInterface;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// The handler is only used to show messages.
if (mHandler == null) {
mHandler = new Handler(this);
}
// Stop the previous session by interrupting the thread.
if (mThread != null) {
mThread.interrupt();
}
// Start a new session by creating a new thread.
mThread = new Thread(this, "ToyVpnThread");
mThread.start();
return START_STICKY;
}
#Override
public void onDestroy() {
if (mThread != null) {
mThread.interrupt();
}
}
#Override
public boolean handleMessage(Message message) {
if (message != null) {
Toast.makeText(this, message.what, Toast.LENGTH_SHORT).show();
}
return true;
}
#Override
public synchronized void run() {
Log.i(TAG, "running vpnService");
try {
runVpnConnection();
} catch (Exception e) {
e.printStackTrace();
//Log.e(TAG, "Got " + e.toString());
} finally {
try {
mInterface.close();
} catch (Exception e) {
// ignore
}
mInterface = null;
mHandler.sendEmptyMessage(R.string.disconnected);
Log.i(TAG, "Exiting");
}
}
private boolean runVpnConnection() throws Exception {
configure();
FileInputStream in = new FileInputStream(mInterface.getFileDescriptor());
// Allocate the buffer for a single packet.
ByteBuffer packet = ByteBuffer.allocate(32767);
// We keep forwarding packets till something goes wrong.
while (true) {
// Assume that we did not make any progress in this iteration.
boolean idle = true;
// Read the outgoing packet from the input stream.
int length = in.read(packet.array());
if (length > 0) {
Log.i(TAG, "************new packet");
System.exit(-1);
while (packet.hasRemaining()) {
Log.i(TAG, "" + packet.get());
//System.out.print((char) packet.get());
}
packet.limit(length);
// tunnel.write(packet);
packet.clear();
// There might be more outgoing packets.
idle = false;
}
Thread.sleep(50);
}
}
public String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
Log.i(TAG, "****** INET ADDRESS ******");
Log.i(TAG, "address: " + inetAddress.getHostAddress());
Log.i(TAG, "hostname: " + inetAddress.getHostName());
Log.i(TAG, "address.toString(): " + inetAddress.getHostAddress().toString());
if (!inetAddress.isLoopbackAddress()) {
//IPAddresses.setText(inetAddress.getHostAddress().toString());
Log.i(TAG, "IS NOT LOOPBACK ADDRESS: " + inetAddress.getHostAddress().toString());
return inetAddress.getHostAddress().toString();
} else {
Log.i(TAG, "It is a loopback address");
}
}
}
} catch (SocketException ex) {
String LOG_TAG = null;
Log.e(LOG_TAG, ex.toString());
}
return null;
}
private void configure() throws Exception {
// If the old interface has exactly the same parameters, use it!
if (mInterface != null) {
Log.i(TAG, "Using the previous interface");
return;
}
// Configure a builder while parsing the parameters.
Builder builder = new Builder();
builder.setMtu(1500);
builder.addAddress(getLocalIpAddress(), 24);
try {
mInterface.close();
} catch (Exception e) {
// ignore
}
mInterface = builder.establish();
}
}
It seems to be receiving packets but I have no idea on how to read the data in the paclkets. the code seems to be incomplete (hence the tunnel.write(packet) that's commented out cause there isn't a variable tunnel). Is this the right way? or is there a better way of doing this?
I'm trying to get two android phones to connect via bluetooth. I'm following the instructions here from the android online howto's, and I'm following pretty closely.
http://developer.android.com/guide/topics/connectivity/bluetooth.html
I can get bluetooth to connect once, but I have to restart the android device or the app itself in order to get it to connect a second time. This is not a problem during development because with each edit of the code the android studio program re-loads the app. It starts it and restarts it, so that during testing I can connect over and over. During actual use I have to restart the android phone or go to the applications manager option under settings and physically stop that app.
From the code below I can connect if I call these lines:
generateDefaultAdapter();
startDiscovery();
startThreadAccept();
startThreadConnect();
How do I get it so that the bluetooth connection can be initiated over and over again? I see the message 'unable to connect' from the inner class 'ConnectThread' and an IO error from a 'printStackTrace()' from that part of the code. The second time I try, I seem to be able to call the method 'stopConnection()' and then the lines above (starting with 'generateDefaultAdapter()') but I find I cannot connect.
package org.test;
//some import statements here...
public class Bluetooth {
public boolean mDebug = true;
public BluetoothAdapter mBluetoothAdapter;
public UUID mUUID = UUID.fromString(BLUETOOTH_UUID);
public Thread mAcceptThread;
public Thread mConnectThread;
public ConnectedThread mManageConnectionAccept;
public ConnectedThread mManageConnectionConnect;
public APDuellingBluetooth() {
}
public void generateDefaultAdapter() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}
if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled() ) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
(mDialogDuel.getActivity()).startActivityForResult(enableBtIntent, INTENT_ACTIVITY_BLUETOOTH_REQUEST_ENABLE);
}
}
public void cancelDiscovery() { if (mBluetoothAdapter != null) mBluetoothAdapter.cancelDiscovery();}
public void startDiscovery() { mBluetoothAdapter.startDiscovery();}
public BluetoothAdapter getBluetoothAdapter() {return mBluetoothAdapter;}
public void stopConnection () {
try {
if (mAcceptThread != null) {
mAcceptThread.interrupt();
//mAcceptThread.join();
mAcceptThread = null;
}
if (mConnectThread != null) {
mConnectThread.interrupt();
//mConnectThread.join();
mConnectThread = null;
}
if (mManageConnectionConnect != null) {
mManageConnectionConnect.cancel();
mManageConnectionConnect.interrupt();
mManageConnectionConnect = null;
}
if (mManageConnectionAccept != null) {
mManageConnectionAccept.cancel();
mManageConnectionAccept.interrupt();
mManageConnectionAccept = null;
}
}
catch(Exception e) {
e.printStackTrace();
}
}
public void startThreadAccept () {
if (mAcceptThread != null && !mAcceptThread.isInterrupted()) {
if (mDebug) System.out.println("server already open");
//return;
mAcceptThread.interrupt();
mAcceptThread = new AcceptThread();
}
else {
mAcceptThread = new AcceptThread();
}
if (mAcceptThread.getState() == Thread.State.NEW ){
//mAcceptThread.getState() == Thread.State.RUNNABLE) {
mAcceptThread.start();
}
}
public void startThreadConnect () {
BluetoothDevice mDevice = mBluetoothAdapter.getRemoteDevice(mChosen.getAddress());
//if (mDebug) System.out.println(mDevice.getAddress() + " -- " + mChosen.getAddress() );
if (mConnectThread != null && !mConnectThread.isInterrupted()) {
if (mDebug) System.out.println("client already open");
//return;
mConnectThread.interrupt();
mConnectThread = new ConnectThread(mDevice);
}
else {
mConnectThread = new ConnectThread(mDevice);
}
if (mConnectThread.getState() == Thread.State.NEW){// ||
//mConnectThread.getState() == Thread.State.RUNNABLE) {
mConnectThread.start();
}
}
public void manageConnectedSocketAccept(BluetoothSocket socket) {
String mTemp = mBluetoothAdapter.getName();
if (mDebug) {
System.out.println("socket accept from " + mTemp);
System.out.println("info accept " + socket.getRemoteDevice().toString());
}
if (mManageConnectionAccept != null && !mManageConnectionAccept.isInterrupted()) {
//mManageConnectionAccept.cancel();
//mManageConnectionAccept.interrupt();
if (mAcceptThread == null) System.out.println(" bad thread accept");
}
else {
mManageConnectionAccept = new ConnectedThread(socket, "accept");
}
if (mManageConnectionAccept.getState() == Thread.State.NEW ){//||
//mManageConnectionAccept.getState() == Thread.State.RUNNABLE) {
mManageConnectionAccept.start();
}
}
public void manageConnectedSocketConnect(BluetoothSocket socket) {
String mTemp = mBluetoothAdapter.getName();
if (mDebug) {
System.out.println("socket connect from " + mTemp);
System.out.println("info connect " + socket.getRemoteDevice().toString());
}
if (mManageConnectionConnect != null && !mManageConnectionConnect.isInterrupted()) {
//mManageConnectionConnect.cancel();
//mManageConnectionConnect.interrupt();
if (mConnectThread == null) System.out.print(" bad thread connect ");
}
else {
mManageConnectionConnect = new ConnectedThread(socket, "connect");
}
if (mManageConnectionConnect.getState() == Thread.State.NEW){// ||
//mManageConnectionConnect.getState() == Thread.State.RUNNABLE) {
mManageConnectionConnect.start();
}
}
public void decodeInput (String mIn, ConnectedThread mSource) {
// do something with info that is returned to me...
}
public void encodeOutput (String mMac1, String mMac2, int mLR1, int mLR2) {
String mTemp = composeOutputString ( mServer, mMac1,mMac2, mLR1, mLR2);
if (mManageConnectionConnect != null && mManageConnectionConnect.isConnected()) {
mManageConnectionConnect.write(mTemp.getBytes());
mManageConnectionConnect.flush();
}
if (mManageConnectionAccept != null && mManageConnectionAccept.isConnected()) {
mManageConnectionAccept.write(mTemp.getBytes());
mManageConnectionAccept.flush();
}
mTemp = composeOutputString ( mClient, mMac1,mMac2, mLR1, mLR2);
if (mManageConnectionConnect != null && mManageConnectionConnect.isConnected()) {
mManageConnectionConnect.write(mTemp.getBytes());
mManageConnectionConnect.flush();
}
if (mManageConnectionAccept != null && mManageConnectionAccept.isConnected()) {
mManageConnectionAccept.write(mTemp.getBytes());
mManageConnectionAccept.flush();
}
}
public String composeOutputString (SocketConnectData mData, String mMac1, String mMac2, int mLR1, int mLR2) {
// make a string here with the data I want to send...
String mTemp = new String();
return mTemp;
}
/////////////////////////////////////////////
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
private boolean mLoop = true;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
mLoop = true;
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(mServiceNameReceive, mUUID );
} catch (IOException e) {
System.out.println("rfcomm problem ");
}
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (mLoop) {
try {
if (mmServerSocket != null) {
socket = mmServerSocket.accept();
}
} catch (IOException e) {
if (mDebug) System.out.println("rfcomm accept problem");
e.printStackTrace();
break;
}
// If a connection was accepted
if (socket != null && ! isConnectionOpen() ) {
// Do work to manage the connection (in a separate thread)
manageConnectedSocketAccept(socket);
try {
mmServerSocket.close();
}
catch (IOException e) {}
break;
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mLoop = false;
mmServerSocket.close();
} catch (IOException e) { }
}
}
/////////////////////////////////////////////
private class ConnectThread extends Thread {
//private final BluetoothSocket mmSocket;
private BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
try {
tmp = device.createRfcommSocketToServiceRecord(mUUID);
if (mDebug) System.out.println("connect -- rf socket to service record " + tmp);
} catch (Exception e) {
System.out.println("exception -- rf socket to service record problem " + tmp);
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
}
//catch (InterruptedException e ) {System.out.println("interrupted exception");}
catch (IOException e) {
// Unable to connect; close the socket and get out
if (mDebug) System.out.println("unable to connect ");
e.printStackTrace(); // <---- I see output from this spot!!
try {
mmSocket.close();
} catch (IOException closeException) {
System.out.println("unable to close connection ");
}
return;
}
// Do work to manage the connection (in a separate thread)
if (mmSocket.isConnected() && ! isConnectionOpen()) {
manageConnectedSocketConnect(mmSocket);
}
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
public boolean isConnected() {
return mmSocket.isConnected();
}
}
/////////////////////////////////////////////
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public String mTypeName = "";
private boolean mLoop = true;
public StringWriter writer;
public ConnectedThread(BluetoothSocket socket, String type) {
mTypeName = type;
mLoop = true;
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
try {
writer = new StringWriter();
}
catch (Exception e) {}
}
public void run() {
byte[] buffer = new byte[1024]; //
int bytes; // bytes returned from read()
String [] mLines ;
// Keep listening to the InputStream until an exception occurs
while (mLoop) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
if (bytes == -1 || bytes == 0) {
if (mDebug) System.out.println("zero read");
return;
}
writer.append(new String(buffer, 0, bytes));
mLines = writer.toString().split("!");
if (mDebug) System.out.println( "lines " +mLines.length);
for (int i = 0; i < mLines.length; i ++ ) {
if (true) {
if (mDebug) System.out.println(" " + mLines[i]);
decodeInput (mLines[i], this);
}
}
} catch (Exception e) {
e.printStackTrace();
if (mDebug) System.out.println("read buffer problem");
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
if (mDebug) System.out.println("bad write");
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mLoop = false;
mmSocket.close();
mmOutStream.close();
mmInStream.close();
} catch (IOException e) { }
}
public boolean isConnected() {
boolean mIsOpen = false;
try {
mIsOpen = mmSocket.isConnected() ;
} catch (Exception e) {}
return mIsOpen;
}
public void flush() {
try {
mmOutStream.flush();
}
catch (IOException e) {e.printStackTrace();}
}
}
///////////////////////////////////////////////
}
Thanks for your time.
EDIT: this is the error msg:
W/System.err﹕ java.io.IOException: read failed, socket might closed or timeout, read ret: -1
W/System.err﹕ at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:553)
W/System.err﹕ at android.bluetooth.BluetoothSocket.waitSocketSignal(BluetoothSocket.java:530)
W/System.err﹕ at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:357)
W/System.err﹕ at org.davidliebman.test.Bluetooth$ConnectThread.run(Bluetooth.java:761)
Try this:
Instead of restarting the app. Turn off the Bluetooth on the Android device and turn it back on after a 5-sec delay. If you could make the connection successfully, it typically a sign that you did not close the connection and socket completely. Log your code. Make sure the closing socket routine is smoothly executed. Check if the IOException you have in your cancel method of your ConnectedThread is not catching any exception:
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
// ADD LOG
mLoop = false;
mmSocket.close();
mmOutStream.close();
mmInStream.close();
// ADD LOG
} catch (IOException e) {
// ADD LOG}
}
Hy , We are working on the android multiplayer game via bluetooth.
It is a multiplayer LUDO game in which 4 player connect to each other and play the game.
We are stuck in connection with the 3rd and 4th player connection.
private OnMaxConnectionsReachedListener maxConnectionsListener = new OnMaxConnectionsReachedListener() {
public void OnMaxConnectionsReached() {
}
};
private OnIncomingConnectionListener connectedListener = new OnIncomingConnectionListener() {
public void OnIncomingConnection(String device) {
//rivalDevice = device;
if(index < 1000)
{
clients[index] = device;
index++;
Log.d("Khawar", "Khawar"+device);
if(index == 1)
{
//blue.setText(clients[0]);
mConnection.sendMessage(clients[0], "ConnectionList--Ludofyp309509--"+server+"--Ludofyp309509--"+clients[0]);
}
else if(index == 2)
{
//blue.setText(clients[0]);
//red.setText(clients[1]);
mConnection.sendMessage(clients[0], "ConnectionList--Ludofyp309509--"+server+"--Ludofyp309509--"+clients[0]+"--Ludofyp309509--"+clients[1]);
mConnection.sendMessage(clients[1], "ConnectionList--Ludofyp309509--"+server+"--Ludofyp309509--"+clients[0]+"--Ludofyp309509--"+clients[1]);
}
else if(index==3)
{
//blue.setText(clients[0]);
//red.setText(clients[1]);
//yellow.setText(clients[2]);
mConnection.sendMessage(clients[0], "ConnectionList--Ludofyp309509--"+server+"--Ludofyp309509--"+clients[0]+"--Ludofyp309509--"+clients[1]+"--Ludofyp309509--"+clients[2]);
mConnection.sendMessage(clients[1], "ConnectionList--Ludofyp309509--"+server+"--Ludofyp309509--"+clients[0]+"--Ludofyp309509--"+clients[1]+"--Ludofyp309509--"+clients[2]);
mConnection.sendMessage(clients[2], "ConnectionList--Ludofyp309509--"+server+"--Ludofyp309509--"+clients[0]+"--Ludofyp309509--"+clients[1]+"--Ludofyp309509--"+clients[2]);
}
}
//Toast.makeText(getBaseContext(), "Client found" + device , Toast.LENGTH_LONG).show();
// WindowManager w = getWindowManager();
// Display d = w.getDefaultDisplay();
// int width = d.getWidth();
//int height = d.getHeight();
}
};
private OnConnectionLostListener disconnectedListener = new OnConnectionLostListener() {
public void OnConnectionLost(String device) {
class displayConnectionLostAlert implements Runnable {
public void run() {
Builder connectionLostAlert = new Builder(self);
connectionLostAlert.setTitle("Connection lost");
connectionLostAlert
.setMessage("Your connection with the other player has been lost.");
connectionLostAlert.setPositiveButton("Ok", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
connectionLostAlert.setCancelable(false);
try {
connectionLostAlert.show();
} catch (BadTokenException e){
Log.v("TAG", "Exception throws here");
}
}
}
self.runOnUiThread(new displayConnectionLostAlert());
}
};
private OnConnectionServiceReadyListener serviceReadyListener = new OnConnectionServiceReadyListener() {
public void OnConnectionServiceReady() {
if (mType == 0) {
mConnection.startServer(1, connectedListener, maxConnectionsListener,
dataReceivedListener, disconnectedListener);
self.setTitle("LudoOverAndroid: " + mConnection.getName() + "-" + mConnection.getAddress());
server = mConnection.getAddress();
green.setText(server);
Log.v("1", server);
// Intent Game = new Intent(self, Board.class);
// .putExtra("TYPE", 1);
// startActivity(Game);
} else {
self.setTitle("LudoOverAndroid: " + mConnection.getName() + "-" + mConnection.getAddress());
Intent serverListIntent = new Intent(self, ServerListActivity.class);
startActivityForResult(serverListIntent, SERVER_LIST_RESULT_CODE);
clients[index] = mConnection.getAddress();
// Intent Game = new Intent(self, Board.class);
// .putExtra("TYPE", 1);
// startActivity(Game);
}
}
};
Above is the sample code where connection are established.
But in the Connection Services class we have the following code
public int connect(String srcApp, String device) throws RemoteException {
if (mApp.length() > 0) {
Log.v("a", "connection service->connect->mApp.length");
return Connection.FAILURE;
}
mApp = srcApp;
BluetoothDevice myBtServer = mBtAdapter.getRemoteDevice(device);
BluetoothSocket myBSock = null;
Log.v("a", "Yaah aya hay aik baar nahe bar bar :");
for (int i = 0; i < Connection.MAX_SUPPORTED && myBSock == null; i++) {
for (int j = 0; j < 3 && myBSock == null; j++) {
myBSock = getConnectedSocket(myBtServer, mUuid.get(i));
if (myBSock == null) {
try {
Log.v("a", "connection service->connect->myBSock==NULL thread sleep");
Thread.sleep(200);
} catch (InterruptedException e) {
Log.e(TAG, "InterruptedException in connect", e);
}
}
}
}
if (myBSock == null) {
Log.v("a", "connection service->connect->myBSock==NULLss");
return Connection.FAILURE;
}
mBtSockets.put(device, myBSock);
mBtDeviceAddresses.add(device);
Thread mBtStreamWatcherThread = new Thread(new BtStreamWatcher(device));
mBtStreamWatcherThread.start();
mBtStreamWatcherThreads.put(device, mBtStreamWatcherThread);
return Connection.SUCCESS;
}
The mobile when connect with the 3rd or 4th device it return myBSock==null.
But if the codes work right it must return the address of the device and
should add mBtDeviceAddresses.add(device); into the server list.
kindly help us to fix the problem.
Thanks in advance
package com.switching.bluetooth;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.switching.ServerMainActivity;
/**
* This class does all the work for setting up and managing Bluetooth
* connections with other devices. It has a thread that listens for incoming
* connections, a thread for connecting with a device, and a thread for
* performing data transmissions when connected.
*/
public class BluetoothService {
// Debugging
private static final String TAG = "BluetoothService iBT";
private static final boolean D = true;
// Name for the SDP record when creating server socket
private static final String NAME = "i BT";
// Unique UUID for this application
private static UUID MY_UUID;
// Member fields
private final BluetoothAdapter mAdapter;
private final Handler mHandler;
private AcceptThread mAcceptThread;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private int mState;
private ArrayList<String> mDeviceAddresses;
private ArrayList<String> mDeviceNames;
private ArrayList<ConnectedThread> mConnThreads;
private ArrayList<BluetoothSocket> mSockets;
/**
* A bluetooth piconet can support up to 7 connections. This array holds 7
* unique UUIDs. When attempting to make a connection, the UUID on the
* client must match one that the server is listening for. When accepting
* incoming connections server listens for all 7 UUIDs. When trying to form
* an outgoing connection, the client tries each UUID one at a time.
*/
private ArrayList<UUID> mUuids;
// Constants that indicate the current connection state
public static final int STATE_NONE = 0; // we're doing nothing
public static final int STATE_LISTEN = 1; // now listening for incoming
// connections
public static final int STATE_CONNECTING = 2; // now initiating an outgoing
// connection
public static final int STATE_CONNECTED = 3; // now connected to a remote
// device
/**
* Constructor. Prepares a new BluetoothChat session.
*
* #param context
* The UI Activity Context
* #param handler
* A Handler to send messages back to the UI Activity
*/
public BluetoothService(Context context, Handler handler) {
mAdapter = BluetoothAdapter.getDefaultAdapter();
mState = STATE_NONE;
mHandler = handler;
initializeArrayLists();
// 7 randomly-generated UUIDs. These must match on both server and
// client.
// mUuids.add(UUID.fromString("b7746a40-c758-4868-aa19-7ac6b3475dfc"));
// mUuids.add(UUID.fromString("2d64189d-5a2c-4511-a074-77f199fd0834"));
// mUuids.add(UUID.fromString("e442e09a-51f3-4a7b-91cb-f638491d1412"));
// mUuids.add(UUID.fromString("a81d6504-4536-49ee-a475-7d96d09439e4"));
// mUuids.add(UUID.fromString("aa91eab1-d8ad-448e-abdb-95ebba4a9b55"));
// mUuids.add(UUID.fromString("4d34da73-d0a4-4f40-ac38-917e0a9dee97"));
// mUuids.add(UUID.fromString("5e14d4df-9c8a-4db7-81e4-c937564c86e0"));
}
public static UUID getMY_UUID() {
return MY_UUID;
}
public static void setMY_UUID(UUID mY_UUID) {
MY_UUID = mY_UUID;
}
public boolean isDeviceConnectedAtPosition(int position) {
if (mConnThreads.get(position) == null) {
return false;
}
return true;
}
private void initializeArrayLists() {
mDeviceAddresses = new ArrayList<String>(5);
mDeviceNames = new ArrayList<String>(5);
mConnThreads = new ArrayList<ConnectedThread>(5);
mSockets = new ArrayList<BluetoothSocket>(5);
mUuids = new ArrayList<UUID>(5);
for (int i = 0; i < 5; i++) {
mDeviceAddresses.add(null);
mDeviceNames.add(null);
mConnThreads.add(null);
mSockets.add(null);
mUuids.add(null);
}
Log.i(TAG, "mConnThreads.size() in Service Constructor--"
+ mConnThreads.size());
}
public ArrayList<String> getmDeviceNames() {
return this.mDeviceNames;
}
public void setmDeviceNames(ArrayList<String> mDeviceNames) {
this.mDeviceNames = mDeviceNames;
}
public ArrayList<String> getmDeviceAddresses() {
return mDeviceAddresses;
}
public void setmDeviceAddresses(ArrayList<String> mDeviceAddresses) {
this.mDeviceAddresses = mDeviceAddresses;
}
/**
* Set the current state of the chat connection
*
* #param state
* An integer defining the current connection state
*/
private synchronized void setState(int state) {
if (D)
Log.d(TAG, "setState() " + mState + " -> " + state);
mState = state;
// Give the new state to the Handler so the UI Activity can update
mHandler.obtainMessage(ServerMainActivity.MESSAGE_STATE_CHANGE, state,
-1).sendToTarget();
}
/**
* Return the current connection state.
*/
public synchronized int getState() {
return mState;
}
/**
* Start the chat service. Specifically start AcceptThread to begin a
* session in listening (server) mode. Called by the Activity onResume()
*/
public synchronized void start() {
if (D)
Log.d(TAG, "start");
// Cancel any thread attempting to make a connection
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
// Start the thread to listen on a BluetoothServerSocket
if (mAcceptThread == null) {
mAcceptThread = new AcceptThread();
mAcceptThread.start();
}
setState(STATE_LISTEN);
}
/**
* Start the ConnectThread to initiate a connection to a remote device.
*
* #param device
* The BluetoothDevice to connect
*/
public synchronized void connect(BluetoothDevice device,
int selectedPosition) {
if (getPositionIndexOfDevice(device) == -1) {
if (D)
Log.d(TAG, "connect to: " + device);
// Cancel any thread attempting to make a connection
if (mState == STATE_CONNECTING) {
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
}
// Cancel any thread currently running a connection
if (mConnThreads.get(selectedPosition) != null) {
mConnThreads.get(selectedPosition).cancel();
// mConnectedThread = null;
mConnThreads.set(selectedPosition, null);
}
// Create a new thread and attempt to connect to each UUID
// one-by-one.
try {
// String
// s="00001101-0000-1000-8000"+device.getAddress().split(":");
ConnectThread mConnectThread = new ConnectThread(device,
UUID.fromString("00001101-0000-1000-8000-"
+ device.getAddress().replace(":", "")),
selectedPosition);
Log.i(TAG, "uuid-string at server side"
+ ("00001101-0000-1000-8000" + device.getAddress()
.replace(":", "")));
mConnectThread.start();
setState(STATE_CONNECTING);
} catch (Exception e) {
}
} else {
Message msg = mHandler
.obtainMessage(ServerMainActivity.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(ServerMainActivity.TOAST,
"This device " + device.getName() + " Already Connected");
msg.setData(bundle);
mHandler.sendMessage(msg);
}
}
/**
* Start the ConnectedThread to begin managing a Bluetooth connection
*
* #param socket
* The BluetoothSocket on which the connection was made
* #param device
* The BluetoothDevice that has been connected
*/
public synchronized void connected(BluetoothSocket socket,
BluetoothDevice device, int selectedPosition) {
if (D)
Log.d(TAG, "connected");
/*
* // Cancel the thread that completed the connection if (mConnectThread
* != null) { mConnectThread.cancel(); mConnectThread = null; }
*
* // Cancel any thread currently running a connection if
* (mConnectedThread != null) { mConnectedThread.cancel();
* mConnectedThread = null; }
*
* // Cancel the accept thread because we only want to connect to one //
* device if (mAcceptThread != null) { mAcceptThread.cancel();
* mAcceptThread = null; }
*/
// Start the thread to manage the connection and perform transmissions
ConnectedThread mConnectedThread = new ConnectedThread(socket);
mConnectedThread.start();
// Add each connected thread to an array
mConnThreads.set(selectedPosition, mConnectedThread);
// Send the name of the connected device back to the UI Activity
Message msg = mHandler
.obtainMessage(ServerMainActivity.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(ServerMainActivity.DEVICE_NAME, device.getName());
msg.setData(bundle);
mHandler.sendMessage(msg);
setState(STATE_CONNECTED);
}
/**
* Stop all threads
*/
public synchronized void stop() {
if (D)
Log.d(TAG, "stop");
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
if (mAcceptThread != null) {
mAcceptThread.cancel();
mAcceptThread = null;
}
for (int i = 0; i < 5; i++) {
mDeviceNames.set(i, null);
mDeviceAddresses.set(i, null);
mSockets.set(i, null);
if (mConnThreads.get(i) != null) {
mConnThreads.get(i).cancel();
mConnThreads.set(i, null);
}
}
setState(STATE_NONE);
}
/**
* Write to the ConnectedThread in an unsynchronized manner
*
* #param out
* The bytes to write
* #see ConnectedThread#write(byte[])
*/
public void write(byte[] out) {
// When writing, try to write out to all connected threads
for (int i = 0; i < mConnThreads.size(); i++) {
try {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (mState != STATE_CONNECTED)
return;
r = mConnThreads.get(i);
}
// Perform the write unsynchronized
r.write(out);
} catch (Exception e) {
}
}
}
/**
* Indicate that the connection attempt failed and notify the UI Activity.
*/
private void connectionFailed() {
setState(STATE_LISTEN);
// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(ServerMainActivity.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(ServerMainActivity.TOAST, "Unable to connect device");
msg.setData(bundle);
mHandler.sendMessage(msg);
}
/**
* Indicate that the connection was lost and notify the UI Activity.
*/
private void connectionLost(BluetoothDevice device) {
// setState(STATE_LISTEN);
int positionIndex = getPositionIndexOfDevice(device);
if (positionIndex != -1) {
Log.i(TAG, "getPositionIndexOfDevice(device) ==="
+ mDeviceAddresses.get(getPositionIndexOfDevice(device)));
mDeviceAddresses.set(positionIndex, null);
mDeviceNames.set(positionIndex, null);
mConnThreads.set(positionIndex, null);
Message msg = mHandler
.obtainMessage(ServerMainActivity.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(ServerMainActivity.TOAST,
"Device connection was lost from " + device.getName());
msg.setData(bundle);
mHandler.sendMessage(msg);
}
// Send a failure message back to the Activity
}
private class AcceptThread extends Thread {
// The local server socket
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
// Create a new listening server socket
try {
if (mAdapter.isEnabled()) {
BluetoothService.setMY_UUID(UUID
.fromString("00001101-0000-1000-8000-"
+ mAdapter.getAddress().replace(":", "")));
}
Log.i(TAG, "MY_UUID.toString()=="
+ BluetoothService.getMY_UUID().toString());
tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME,
BluetoothService.getMY_UUID());
} catch (IOException e) {
Log.e(TAG, "listen() failed", e);
}
mmServerSocket = tmp;
}
public void run() {
if (D)
Log.d(TAG, "BEGIN mAcceptThread" + this);
setName("AcceptThread");
BluetoothSocket socket = null;
Log.i(TAG, "mState in acceptThread==" + mState);
// Listen to the server socket if we're not connected
while (mState != STATE_CONNECTED) {
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket = mmServerSocket.accept();
} catch (IOException e) {
Log.e(TAG, "accept() failed", e);
break;
}
// If a connection was accepted
if (socket != null) {
synchronized (BluetoothService.this) {
switch (mState) {
case STATE_LISTEN:
case STATE_CONNECTING:
// Situation normal. Start the connected thread.
connected(socket, socket.getRemoteDevice(),getAvailablePositionIndexForNewConnection(socket.getRemoteDevice()));
break;
case STATE_NONE:
case STATE_CONNECTED:
// Either not ready or already connected. Terminate
// new socket.
try {
socket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close unwanted socket", e);
}
break;
}
}
}
}
if (D)
Log.i(TAG, "END mAcceptThread");
}
public void cancel() {
if (D)
Log.d(TAG, "cancel " + this);
try {
mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of server failed", e);
}
}
}
/**
* This thread runs while listening for incoming connections. It behaves
* like a server-side client. It runs until a connection is accepted (or
* until cancelled).
*/
// private class AcceptThread extends Thread {
// BluetoothServerSocket serverSocket = null;
//
// public AcceptThread() {
// }
//
// public void run() {
// if (D)
// Log.d(TAG, "BEGIN mAcceptThread" + this);
// setName("AcceptThread");
// BluetoothSocket socket = null;
// try {
// // Listen for all 7 UUIDs
// serverSocket = mAdapter.listenUsingRfcommWithServiceRecord(
// NAME, MY_UUID);
// socket = serverSocket.accept();
// if (socket != null) {
// String address = socket.getRemoteDevice().getAddress();
// mSockets.add(socket);
// mDeviceAddresses.add(address);
// mDeviceNames.add(socket.getRemoteDevice().getName());
// // connected(socket, socket.getRemoteDevice());
// }
// } catch (IOException e) {
// Log.e(TAG, "accept() failed", e);
// }
// if (D)
// Log.i(TAG, "END mAcceptThread");
// }
//
// public void cancel() {
// if (D)
// Log.d(TAG, "cancel " + this);
// try {
// serverSocket.close();
// } catch (IOException e) {
// Log.e(TAG, "close() of server failed", e);
// }
// }
// }
/**
* This thread runs while attempting to make an outgoing connection with a
* device. It runs straight through; the connection either succeeds or
* fails.
*/
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private UUID tempUuid;
private int selectedPosition;
public ConnectThread(BluetoothDevice device, UUID uuidToTry,
int selectedPosition) {
mmDevice = device;
BluetoothSocket tmp = null;
tempUuid = uuidToTry;
this.selectedPosition = selectedPosition;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(uuidToTry);
} catch (IOException e) {
Log.e(TAG, "create() failed", e);
}
mmSocket = tmp;
}
public void run() {
Log.i(TAG, "BEGIN mConnectThread");
setName("ConnectThread");
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
// if
// (tempUuid.toString().contentEquals(mUuids.get(6).toString()))
// {
connectionFailed();
// }
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
Log.e(TAG,
"unable to close() socket during connection failure",
e2);
}
// Start the service over to restart listening mode
BluetoothService.this.start();
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothService.this) {
mConnectThread = null;
}
mDeviceAddresses.set(selectedPosition, mmDevice.getAddress());
mDeviceNames.set(selectedPosition, mmDevice.getName());
// Start the connected thread
connected(mmSocket, mmDevice, selectedPosition);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
/**
* This thread runs during a connection with a remote device. It handles all
* incoming and outgoing transmissions.
*/
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "create ConnectedThread");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(
ServerMainActivity.MESSAGE_READ,
bytes,
getPositionIndexOfDevice(mmSocket.getRemoteDevice()),
buffer).sendToTarget();
Log.i("**********read", "read Called........");
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost(mmSocket.getRemoteDevice());
break;
}
}
}
/**
* Write to the connected OutStream.
*
* #param buffer
* The bytes to write
*/
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
mHandler.obtainMessage(ServerMainActivity.MESSAGE_WRITE, -1,
-1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
public int getPositionIndexOfDevice(BluetoothDevice device) {
for (int i = 0; i < mDeviceAddresses.size(); i++) {
if (mDeviceAddresses.get(i) != null
&& mDeviceAddresses.get(i).equalsIgnoreCase(
device.getAddress()))
return i;
}
return -1;
}
public int getAvailablePositionIndexForNewConnection(BluetoothDevice device) {
if (getPositionIndexOfDevice(device) == -1) {
for (int i = 0; i < mDeviceAddresses.size(); i++) {
if (mDeviceAddresses.get(i) == null) {
return i;
}
}
}
return -1;
}
}
I implemented that with sucess after a relevant amount of work, during the path i faced some tricky bugs, for instance I had to implement a Handshake protocol(something like that) to avoid timeout problem during a connection attempt.
Well, I started looking at the BluetoothChat example(Android SDK Sample), that implements communication between 2 devices. So, I modified that, to permit multiple connections. As the code became large, i will just tell you the approach I have used.
Basically, all devices running my app can be a server or client. So each one, has always a BluetoothServerSocket(AcceptThread) running, so in this way, each device is always able to receive a request connection.
A device that wants to connect, starts a ConnectThread, this thread it is started after a discovery process or if it choose BluetoothDevice of PairedDevices Using getBondedDevices.
When a connection is established, I create a new Thread(ConnectedThread) that represents that connection. If you want to has different behavior that depends of you device role(master or slave) you can have a ConnectedThread subclass like MasterThread and SlaveThread
The Android Documentation has a good explanation of how to work with Bluetooth at: http://developer.android.com/guide/topics/connectivity/bluetooth.html
I have an app which works with UDP packets. So I want to send and receive UDP packets at the same time in the same app. Is it real? Now it works perfectly, but separately.
Code snippet:
UDP Server:
public class UDPServer {
DatagramPacket packet;
DatagramSocket socket;
static int port = 11111;
private boolean isRun = false;
private String message = "";
private int broadcastInterval;
private Context context;
public boolean IsRunUDPServer(){
return isRun;
}
public void StopBroadcasting(){
isRun = false;
}
public void StartBroadcasting(String message, int broadcastInterval){
isRun = true;
this.message = message;
this.broadcastInterval = broadcastInterval;
new Thread(runner).start();
}
Runnable runner = new Runnable() {
public void run() {
while(isRun){
try {
//Sending(message);
SendBroadcastMessageOverWiFi(message);
Thread.sleep(broadcastInterval);
Log.e("SendBroadcastMessageOverWiFi", message);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
}
}
if(socket!=null){
socket.disconnect();
socket.close();
}
}
};
public UDPServer(Context context) {
this.context=context;
}
private InetAddress getBroadcastAddress() throws IOException {
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcp = wifi.getDhcpInfo();
// handle null somehow
if(dhcp==null){ return null; }
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads);
}
private void SendBroadcastMessageOverWiFi(String message) throws IOException{
InetAddress addr = getBroadcastAddress();
if(addr!=null){
if(socket==null){
socket = new DatagramSocket(port);
socket.setBroadcast(true);
}
DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length,
addr, port);
socket.send(packet);
}
}}
UDP Client:
public class UDPClient {
MulticastSocket socket;
InetAddress groupAddress;
DatagramPacket packet;
byte[] buffer;
private static final int UDP_SERVER_PORT = 11111;
private static final int MAX_UDP_DATAGRAM_LEN = 32768;
public interface OnReceiveDataListener{
public abstract void onReceiveData(String data);
}
private OnReceiveDataListener ReceiveDataListener = null;
public void setReceiveDataListener(OnReceiveDataListener ReceiveDataListener) {
this.ReceiveDataListener = ReceiveDataListener;
}
public OnReceiveDataListener getReceiveDataListener() {
return ReceiveDataListener;
}
private boolean isRun = false;
private Thread broadcastReceiver;
public void StopReceiving(){
isRun = false;
}
public void StartReceiving(){
isRun = true;
buffer = new byte[4096];
broadcastReceiver = new Thread(runner);
broadcastReceiver.start();
}
Runnable runner = new Runnable() {
#Override
public void run() {
while(isRun){
String lText;
packet = new DatagramPacket(buffer, buffer.length);
DatagramSocket ds = null;
try {
ds = new DatagramSocket(UDP_SERVER_PORT);
ds.receive(packet);
lText = new String(packet.getData(), 0, packet.getLength());
Log.i("UDP packet received", lText+" "+packet.getLength()+" "+packet.getData().length);
if(getReceiveDataListener()!=null)
getReceiveDataListener().onReceiveData(lText);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ds != null) {
ds.close();
}
}
}
}
};}
If I start server, the client won't be able receive udp packets.
Please help me. Thank you.
Only one socket (in one process) can bind to a given UDP port at one time. It is not permitted to have two sockets bind to the same UDP port number.
In most cases, there is no reason to have the client bound to a specific port. Instead, specify port 0 (INADDR_ANY) and the system will assign an unused dynamic port.