Make Bluetooth connection alive for multiple activity

1k views Asked by At

In my application i want to send value from multiple activity to connected Thread,i don't know to solve this problem please help me Example: I want to send String string ="#FFFFFF000*";from First-activity to service class, String string= "#000000000*" ;from Second- activity to service class

 public class BluetoothDataService1 extends Service {
        final int handlerState = 0;
        Handler bluetoothIn;
        private BluetoothAdapter btAdapter = null;

        private ConnectingThread mConnectingThread;
        private ConnectedThread mConnectedThread;

        private boolean stopThread;

        private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

       // private static String MAC_ADDRESS="98:D3:31:30:A5:00" ;
        private static String MAC_ADDRESS="98:D3:32:20:42:54" ;

        private StringBuilder recDataString = new StringBuilder();
        private final IBinder binder = new LocalBinder();


        @Override
        public void onCreate() {
            super.onCreate();

            stopThread = false;

        }


        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            super.onStartCommand(intent, flags, startId);
            bluetoothIn = new Handler()
            {
                public void handleMessage(android.os.Message msg) {

                    if (msg.what == handlerState) {
                        String readMessage = (String) msg.obj;
                        recDataString.append(readMessage);


                    }
                    recDataString.delete(0, recDataString.length());
                }


            };

            btAdapter = BluetoothAdapter.getDefaultAdapter();
            checkBTState();
            return START_STICKY;
            //return super.onStartCommand(intent, flags, startId);
        }



        @Override
        public void onDestroy() {
            super.onDestroy();
            bluetoothIn.removeCallbacksAndMessages(null);
            stopThread = true;
            if (mConnectedThread != null ) {
                mConnectedThread.closeStreams();
            }
            if (mConnectingThread != null) {
                mConnectingThread.closeSocket();
            }

        }


        @Override
        public IBinder onBind(Intent intent)

        {
            return binder;
        }


        //Checks  Bluetooth is available and turned on /off
        private void checkBTState() {
            if (btAdapter == null) {

                stopSelf();
            } else {
                if (btAdapter.isEnabled()) {

                    try {
                        BluetoothDevice device = btAdapter.getRemoteDevice(MAC_ADDRESS);
                        mConnectingThread = new ConnectingThread(device);
                        mConnectingThread.start();
                    }   catch (IllegalArgumentException e) {

                        stopSelf();
                    }
                }   else {

                    stopSelf();
                }
            }
        }

    //    public void senddata() {
    //
    //    }

        // New Class for Connecting Thread
           public class ConnectingThread extends Thread {
            private final BluetoothSocket mmSocket;
            private final BluetoothDevice mmDevice;
            public ConnectingThread(BluetoothDevice device) {

                mmDevice = device;
                BluetoothSocket temp = null;

                try {

                    temp = mmDevice.createRfcommSocketToServiceRecord(BTMODULEUUID);

                }   catch (IOException e) {

                    stopSelf();
                }
                mmSocket = temp;
            }

            @Override
            public void run() {
                super.run();
                btAdapter.cancelDiscovery();
                try {
                    mmSocket.connect();
                    mConnectedThread = new ConnectedThread(mmSocket);
                    mConnectedThread.start();
                    mConnectedThread.write("x");
                } catch (IOException e) {
                    try {

                        mmSocket.close();
                        stopSelf();
                    } catch (IOException e2) {

                        stopSelf();

                    }
                } catch (IllegalStateException e) {

                    stopSelf();
                }
            }
            public void closeSocket() {
                try {

                    mmSocket.close();
                } catch (IOException e2) {

                    stopSelf();
                }
            }
        }

        // New Class for Connected Thread
        class ConnectedThread extends Thread {
            private final InputStream mmInStream;
            private final OutputStream mmOutStream;

            //creation of the connect thread
            public ConnectedThread(BluetoothSocket socket) {

                InputStream tmpIn = null;
                OutputStream tmpOut = null;

                try {
                    //Create I/O streams for connection
                    tmpIn = socket.getInputStream();
                    tmpOut = socket.getOutputStream();
                }   catch (IOException e) {

                    stopSelf();
                }

                mmInStream = tmpIn;
                mmOutStream = tmpOut;
            }

            public void run() {

                byte[] buffer = new byte[256];
                int bytes;

                // Keep looping to listen for received messages
                while (true && !stopThread) {
                    try {
                        bytes = mmInStream.read(buffer);
                        String readMessage = new String(buffer, 0, bytes);
                        //Send the obtained bytes to the UI Activity via handler
                        bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
                    }   catch (IOException e) {

                        stopSelf();
                        break;
                    }
                }
            }

            //write method
            public void write(String input) {
                byte[] msgBuffer = input.getBytes();
                try {
                    mmOutStream.write(msgBuffer);
                }   catch (IOException e) {
                    stopSelf();
                }
            }

            public void closeStreams() {
                try {
                    mmInStream.close();
                    mmOutStream.close();
                }   catch (IOException e2) {
                    stopSelf();
                }
            }
        }

    //    private class LocalBinder implements IBinder {
    //    }
    public class LocalBinder extends Binder {
              BluetoothDataService1 getService() {
                 return BluetoothDataService1.this;
        }
    }

This is my Activity

public class SendActivity extends Activity implements View.OnClickListener {
    Button on;
    BluetoothDataService1 bluetoothDataService1;
    public boolean isBound = false;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send);
        on= (Button) findViewById(R.id.btnon);
        on.setOnClickListener(this);
    }

    @Override
    public  void onStart() {
        super.onStart();
          Intent intent = new Intent(this, BluetoothDataService1.class);
          bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onClick(View v) {
        if (isBound) {

//                  Intent intent=new Intent (SendActivity.this,BluetoothDataService1.class);
//                  intent.putExtra("ON","#ffffff00" );
//                  startService(intent);
        }
    }
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            BluetoothDataService1.LocalBinder binder = (BluetoothDataService1.LocalBinder) service;
            bluetoothDataService1 = binder.getService();
            isBound = true;

        }
        @Override
             public void onServiceDisconnected(ComponentName arg0) {
             isBound = false;
        }
    };
    @Override
      public void onStop() {
        super.onStop();
          if (isBound) {
              unbindService(connection);
              isBound = false;
        }
    }
1

There are 1 answers

2
Yogesh Borhade On
  1. whatever i have understand from your question i am giving solution to you 2.you must need to make variable static so that u can directly access that variable from other activity 3.like you have 3 activity A B C 4.now you want fetch variable from A and B into C
    1. then you can make variable static in A and B check below.
    2. in A public static String string="#FFFFFF000" same as in B
    3. and you can acess it into C
    4. String string =A.string;
  2. or you can create static method into A activity and B activity and call that method from C activity. publi
  3. like `public static void send(){ static veriableName="FFFFFF000" // sending code here whatever

               }`
    
  4. and by calling this method from C you can do A.send();