Send messages to Handler from other activity

I Have a code that connects to a bluetooth device, opens a bluetooth socket that communicates with a running thread which operates functions running in main activity.
I would like to move all the connecting sequence to another activity, and then operate the thread from the main one as done now. The problem is they are all connected.
I would like to have the option of sending a message between these activities(meaning remaining the socket operating from the other activity), i.e this message:
mHandler.obtainMessage(CONNECTING_STATUS, 1, -1, name)
.sendToTarget();

because it is impossible to pass handler between activities I don’t know how/if possible to do so.
What is the best way of doing such a thing?
added part of the code.
Thanks.

    mHandler = new Handler(){
        public void handleMessage(android.os.Message msg){
            if(msg.what == MESSAGE_READ){
                String readMessage = null;
                try {
                    readMessage = new String((byte[]) msg.obj, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                RxMessage = readMessage.split(" ");
                if (sH.isStringInCorrectOrder(RxMessage,Weight))
                    populateListView(RxMessage);
                mReadBuffer.setText(readMessage);
            }

            if(msg.what == CONNECTING_STATUS){
                if(msg.arg1 == 1)
                    mBluetoothStatus.setText("Connected to Device: " + (String)(msg.obj));
                else
                    mBluetoothStatus.setText("Connection Failed");
            }
        }
    };

private void connectBT (){
    mBluetoothStatus.setText("Connecting...");
    // Get the device MAC address, which is the last 17 chars in the View
    final String address = "98:D3:31:30:39:75";
    final String name = "HC-06";

    // Spawn a new thread to avoid blocking the GUI one
    new Thread()
    {
        public void run() {
            boolean fail = false;

            BluetoothDevice device = mBTAdapter.getRemoteDevice(address);

            try {
                mBTSocket = createBluetoothSocket(device);
            } catch (IOException e) {
                fail = true;
                Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
            }
            // Establish the Bluetooth socket connection.
            try {
                mBTSocket.connect();
            } catch (IOException e) {
                try {
                    fail = true;
                    mBTSocket.close();
                    mHandler.obtainMessage(CONNECTING_STATUS, -1, -1)
                            .sendToTarget();
                } catch (IOException e2) {
                    //insert code to deal with this
                    Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
                }
            }
            if(fail == false) {
                mConnectedThread = new ConnectedThread(mBTSocket);
                mConnectedThread.start();

                mHandler.obtainMessage(CONNECTING_STATUS, 1, -1, name)
                        .sendToTarget();
            }
        }
    }.start();
}


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;

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

    public void run() {
        byte[] buffer = new byte[1024];  // buffer store for the stream
        int bytes; // bytes returned from read()
        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.available();
                if(bytes != 0) {
                    SystemClock.sleep(100); //pause and wait for rest of data. Adjust this depending on your sending speed.
                    bytes = mmInStream.available(); // how many bytes are ready to be read?
                    bytes = mmInStream.read(buffer, 0, bytes); // record how many bytes we actually read
                    mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                            .sendToTarget(); // Send the obtained bytes to the UI activity
                }
            } catch (IOException e) {
                e.printStackTrace();

                break;
            }
        }
    }

    /* Call this from the main activity to send data to the remote device */
    public void write(String input) {
        byte[] bytes = input.getBytes();           //converts entered String into bytes
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

Just declare mHandler as static and you can access it from all other activities. This will create a small temporary memory leak, but don’t worry about it.