从其他活动向处理程序发送消息

时间:2019-08-04 12:08:18

标签: java android android-studio sockets bluetooth

我有一个连接到蓝牙设备的代码,打开一个蓝牙套接字,该套接字与正在运行的线程通信,该线程操作在主活动中运行的功能。 我想将所有连接序列移至另一活动,然后像现在一样从主线程操作线程。问题是它们都已连接。 我想选择在这些活动之间发送消息(意味着保持套接字在其他活动中运行),即此消息: mHandler.obtainMessage(CONNECTING_STATUS,1,-1,名称)                         .sendToTarget();

因为不可能在活动之间传递处理程序,我不知道如何/如果可能的话。 做这种事情的最好方法是什么? 添加了部分代码。 谢谢。

    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 个答案:

答案 0 :(得分:0)

只需将mHandler声明为static,您就可以从所有其他活动中访问它。这将造成少量的临时内存泄漏,但是请不必担心。