Need information on moving Bluetooth connectivity code to a service

Tip / Sign in to post questions, reply, level up, and achieve exciting badges. Know more

cross mob
Anonymous
Not applicable

     Hi, I am trying to a WICED SENSE device as soon as as it gets disconnected. To be precise, if a bluetooth device gets disconnected the WICED sense app should search for the device and connect without any user  interaction.

Now I am able to connect to the device through the device picker, after selecting the WICED senese device i store the MAC address of that device. Next, the wiced sense device gets connected and paired. Later, if the device gets disconnected while the app is running an service should start search for the device with matching MAC address and connect to it if available.

The following is code I have implemented to get the connectivity through a service

public class BluetoothConnect extends Service {

        private BluetoothAdapter mBluetoothAdapter;

        public static final String BT_DEVICE = "btdevice";

        public static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";

        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
        private ConnectThread mConnectThread;

        private static ConnectedThread mConnectedThread;

        // public mInHangler mHandler = new mInHangler(this);
        private static Handler mHandler = null;

        public static int mState = STATE_NONE;

        public static String deviceName;

        public static BluetoothClass.Device device = null;

        @Override
        public void onCreate() {

            Log.d("BluetoothConnect", "Service started");

             super.onCreate();

       }

        @Override
        public IBinder onBind(Intent intent) {

             // mHandler = ((MyAplication) getApplication()).getHandler();
             return mBinder;

       }

        public class LocalBinder extends Binder {

            BluetoothConnect getService() {

            return BluetoothConnect.this;

            }

       }

        private final IBinder mBinder = new LocalBinder();

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {

            Log.d("BluetoothConnect", "Onstart Command");

            String BT_DEVICE = "btdevice";

             mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

             if (mBluetoothAdapter != null) {

             device = (BluetoothClass.Device) intent.getSerializableExtra(BT_DEVICE);

             //deviceName = device.getDeviceName();
             final SharedPreferences mSharedPreference2= PreferenceManager.getDefaultSharedPreferences(getBaseContext());

            String value2=(mSharedPreference2.getString("MAC_ID", ""));

            String macAddress = value2;

             if (macAddress != null && macAddress.length() > 0) {

                      connectToDevice(macAddress);

            } else {

                      stopSelf();

             return 0;

            }    

       }

       String stopservice = intent.getStringExtra("stopservice");

        if (stopservice != null && stopservice.length() > 0) {

       stop();

       }

        return START_STICKY;

       }

        private synchronized void connectToDevice(String macAddress) {

            BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(macAddress);

             if (mState == STATE_CONNECTING) {

             if (mConnectThread != null) {

                  mConnectThread.cancel();

                  mConnectThread = null;

                 }

            }

   // Cancel any thread currently running a connection
            if (mConnectedThread != null) {

                 mConnectedThread.cancel();

                 mConnectedThread = null;

            }

             mConnectThread = new ConnectThread(device);

             mConnectThread.start();

            setState(STATE_CONNECTING);

    }

        private void setState(int state) {

            BluetoothConnect.mState = state;

        }

        public synchronized void stop() {

            setState(STATE_NONE);

             if (mConnectThread != null) {

             mConnectThread.cancel();

             mConnectThread = null;

            }

        if (mConnectedThread != null) {

             mConnectedThread.cancel();

             mConnectedThread = null;

       }

        if (mBluetoothAdapter != null) {

        mBluetoothAdapter.cancelDiscovery();

       }

       stopSelf();

       }

        @Override
             public boolean stopService(Intent name) {

                 setState(STATE_NONE);

                  if (mConnectThread != null) {

                       mConnectThread.cancel();

                       mConnectThread = null;

                 }

                  if (mConnectedThread != null) {

                       mConnectedThread.cancel();

                       mConnectedThread = null;

                     }

             mBluetoothAdapter.cancelDiscovery();

             return super.stopService(name);

       }

        private void connectionFailed() {

            BluetoothConnect.this.stop();

          }

        private void connectionLost() {

            BluetoothConnect.this.stop();

           }

        private static Object obj = new Object();

        public static void write(byte[] out) {

        // Create temporary object
        ConnectedThread r;

   // Synchronize a copy of the ConnectedThread
        synchronized (obj) {

        if (mState != STATE_CONNECTED)

             return;

            r = mConnectedThread;

           }

             // Perform the write unsynchronized
        r.write(out);

       }

        private synchronized void connected(BluetoothSocket mmSocket, BluetoothDevice mmDevice) {

        // 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;

       }

    

        mConnectedThread = new ConnectedThread(mmSocket);

        mConnectedThread.start();

        setState(STATE_CONNECTED);

       }

        private class ConnectThread extends Thread {

        private final BluetoothSocket mmSocket;

        private final BluetoothDevice mmDevice;

        public ConnectThread(BluetoothDevice device) {

        this.mmDevice = device;

       BluetoothSocket tmp = null;

        try {

            tmp = device.createRfcommSocketToServiceRecord(UUID.fromString(SPP_UUID));

            } catch (IOException e) {

                 e.printStackTrace();

            }

             mmSocket = tmp;

       }

        @Override
        public void run() {

            setName("ConnectThread");

            mBluetoothAdapter.cancelDiscovery();

             try {

             mmSocket.connect();

            } catch (IOException e) {

             try {

             mmSocket.close();

            } catch (IOException e1) {

            e1.printStackTrace();

        }

       connectionFailed();

        return;

       }

        synchronized (BluetoothConnect.this) {

        mConnectThread = null;

       }

       connected(mmSocket, mmDevice);

       }

        public void cancel() {

           try {

             mmSocket.close();

            } catch (IOException e) {

                 Log.e("BluetoothConnect", "close() of connect socket failed", e);

                 }

            }

       }

        private class ConnectedThread extends Thread {

        private final BluetoothSocket mmSocket;

        private final InputStream mmInStream;

        private final OutputStream mmOutStream;

        public ConnectedThread(BluetoothSocket socket) {

        mmSocket = socket;

        InputStream tmpIn = null;

        OutputStream tmpOut = null;

        try {

            tmpIn = socket.getInputStream();

            tmpOut = socket.getOutputStream();

            } catch (IOException e) {

            Log.e("Printer Service", "temp sockets not created", e);

            }

        mmInStream = tmpIn;

        mmOutStream = tmpOut;

       }

        private byte[] btBuff;

        public void write(byte[] buffer) {

             try {

             mmOutStream.write(buffer);

        // Share the sent message back to the UI Activity
        mHandler.obtainMessage(MainActivity.MESSAGE_WRITE, buffer.length, -1, buffer).sendToTarget();

       } catch (IOException e) {

            Log.e("BluetoothConnect", "Exception during write", e);

            }

       }

        public void cancel() {

             try {

                  mmSocket.close();

                 } catch (IOException e) {

                 Log.e("BluetoothConnect", "close() of connect socket failed", e);

                 }

            }

       }

        public void trace(String msg) {

            Log.d("AbstractActivity", msg);

            toast(msg);

       }

        public void toast(String msg) {

            Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();

  }

        @Override
        public void onDestroy() {

            stop();

            Log.d("Printer Service", "Destroyed");

             super.onDestroy();

  }

        private void sendMsg(int flag) {

            Message msg = new Message();

            msg.what = flag;

             handler.sendMessage(msg);

  }

        private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {//
             if (!Thread.currentThread().isInterrupted()) {

             switch (msg.what) {

             case 3:

             break;

            case 4:

             break;

             case 5:

             break;

             case -1:

             break;

            }

            }

             super.handleMessage(msg);

            }    

       };

   }

The above code is the service code for auto connection. I want to know whether I am going in the right direction or not. Any kind of help is appreciated.

0 Likes
2 Replies