I need to connect my Android to a Bluetooth device. I am using a sample bluetooth chat from google.
I am having problems with this using Google Nexus because Nexus made a connection but disconnected immediately. I need to initiate the connection twice as a workaround (see ConnectionLost ()).
Now it works great on both the Nexus One and HTC Desire.
My problem is disconnecting when the application exits. It works great on Nexus, the connection is closed, but not on HTC Desire. I am adding a function to close the input / output stream in addition to closing the socket. Take a look at the stop () function.
package xxx.yyy.zzz;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import activities.Act_Main;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
public class BluetoothService {
private static final String TAG = "BluetoothService";
private static final boolean D = true;
private final Handler mHandler;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private int mState;
private String mBTAddress;
private boolean isStop = false;
public static final int STATE_NONE = 0;
public static final int STATE_LISTEN = 1;
public static final int STATE_CONNECTING = 2;
public static final int STATE_CONNECTED = 3;
public BluetoothService(Context context, Handler handler)
{
mState = STATE_NONE;
mHandler = handler;
}
private synchronized void setState(int state)
{
if (D) Log.d(TAG, "setState() " + mState + " -> " + state);
mState = state;
mHandler.obtainMessage(Act_Main.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
}
public synchronized int getState()
{
return mState;
}
public synchronized void connect(String BTAddress)
{
mBTAddress = BTAddress ;
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(BTAddress);
if (D) Log.d(TAG, "connect to: " + device);
if (mState == STATE_CONNECTING)
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
mConnectThread = new ConnectThread(device);
mConnectThread.start();
setState(STATE_CONNECTING);
isStop = false ;
}
public synchronized void connected(BluetoothSocket socket, BluetoothDevice device)
{
if (D) Log.d(TAG, "connected");
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
mConnectedThread = new ConnectedThread(socket);
mConnectedThread.start();
Message msg = mHandler.obtainMessage(Act_Main.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(Act_Main.DEVICE_NAME, device.getName());
msg.setData(bundle);
mHandler.sendMessage(msg);
setState(STATE_CONNECTED);
}
public synchronized void stop()
{
isStop = true ;
if (D)
Log.d(TAG, "stop");
if(mConnectThread != null)
{
mConnectThread.cancel();
Thread moribund = mConnectThread;
mConnectThread = null;
moribund.interrupt();
}
if(mConnectedThread != null)
{
mConnectedThread.cancel();
Thread moribund = mConnectedThread;
mConnectedThread = null;
moribund.interrupt();
}
setState(STATE_NONE);
}
public void write(byte[] out)
{
ConnectedThread r;
synchronized (this)
{
Log.d(TAG, "BT_SEND_MESSAGE");
if (mState != STATE_CONNECTED)
return;
r = mConnectedThread;
}
r.write(out);
}
private void connectionFailed()
{
try
{
synchronized (this)
{
this.wait(3000);
}
connect(mBTAddress);
}
catch(InterruptedException ex)
{
Log.e(TAG, "WAIT_EXCEPTION:"+ ex.getMessage());
}
}
private void connectionLost()
{
if (!isStop)
connect(mBTAddress);
}
private class ConnectThread extends Thread
{
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device)
{
mmDevice = device;
BluetoothSocket tmp = null;
try
{
tmp = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
}
catch (Exception e)
{
Log.e(TAG, "create() failed", e);
}
mmSocket = tmp;
}
public void run()
{
Log.i(TAG, "BEGIN mConnectThread");
setName("ConnectThread");
try
{
mmSocket.connect();
}
catch (IOException e)
{
connectionFailed();
try
{
mmSocket.close();
}
catch (IOException e2)
{
Log.e(TAG, "unable to close() socket during connection failure", e2);
}
return;
}
synchronized (BluetoothService.this)
{
mConnectThread = null;
}
connected(mmSocket, mmDevice);
}
public void cancel()
{
try
{
mmSocket.close();
}
catch (IOException e)
{
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
private class ConnectedThread extends Thread {
private BluetoothSocket mmSocket;
private InputStream mmInStream;
private OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "create ConnectedThread");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
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;
int bytes = 0;
while (true)
{
try
{
buffer = new byte[1024];
bytes = mmInStream.read(buffer);
mHandler.obtainMessage(Act_Main.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
}
catch (IOException e)
{
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
public void write(byte[] buffer)
{
try
{
mmOutStream.write(buffer);
}
catch (IOException e)
{
Log.e(TAG, "Exception during write", e);
}
}
public void cancel()
{
if (mmOutStream != null)
{
try {mmOutStream.close();} catch (Exception e) { Log.e(TAG, "close() of outputstream failed", e); }
mmOutStream = null;
}
if (mmInStream != null)
{
try {mmInStream.close();} catch (Exception e) { Log.e(TAG, "close() of inputstream failed", e); }
mmInStream = null;
}
if (mmSocket != null)
{
try {mmSocket.close();} catch (Exception e) { Log.e(TAG, "close() of connect socket failed", e); }
mmSocket = null;
}
}
}
}
Thanks in advance for your help.
Jj