简体   繁体   English

Android蓝牙发送/接收hashmap

[英]Android bluetooth send/receive a hashmap

I'm trying to send a hashmap from one device to another via bluetooth. 我正在尝试通过蓝牙将一个hashmap从一个设备发送到另一个设备。 I'm creating the hashmap like this, and then calling the connection threads writeObject method: 我正在创建这样的hashmap,然后调用连接线程writeObject方法:

Map<String,String> subInfo = new HashMap<>();
subInfo.put("type", "subInfo");
subInfo.put("num", "1");
BTService.connectedThread.writeObject(subInfo);

My bluetooth service has the following class thats used to handle data transfer between devices in a background thread: 我的蓝牙服务有以下类用于处理后台线程中设备之间的数据传输:

public static class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
        private final ObjectInputStream mmObjInStream;
        private final ObjectOutputStream mmObjOutStream;

        public ConnectedThread(BluetoothSocket socket) {
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
            ObjectInputStream tmpObjIn = null;
            ObjectOutputStream tmpObjOut = null;

            // Get the input and output streams, using temp objects because
            // member streams are final
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
                tmpObjIn = new ObjectInputStream(socket.getInputStream());
                tmpObjOut = new ObjectOutputStream(socket.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
            mmObjInStream = tmpObjIn;
            mmObjOutStream = tmpObjOut;
        }

        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 (!this.isInterrupted()) {
                try {
                    // Read from the InputStream
                    bytes = mmInStream.read(buffer);
                    // Send the obtained bytes to the UI activity
                    mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer)
                            .sendToTarget();
                } catch (IOException e) {
                    e.printStackTrace();
                    break;
                }

                try {
                    //Read objects from ObjectInputStream
                    Object object = mmObjInStream.readObject();
                    // Send the obtained object to the UI activity
                    mHandler.obtainMessage(Constants.MESSAGE_READ_OBJECT, -1, 0, object)
                            .sendToTarget();
                } catch (ClassNotFoundException | IOException e) {
                    e.printStackTrace();
                }
            }
        }

        /* Call this from the main activity to send data to the remote device */
        public void write(byte[] bytes) {
            try {
                mmOutStream.write(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void writeObject(Object object) {
            try {
                mmObjOutStream.writeObject(object);
            }catch(Exception e){
                Log.e(TAG, "Error ObjectOutputStream: " + e.getLocalizedMessage());
            }
        }

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

So when I call the writeObject method it should send the object down the Object output stream of the thread above. 因此,当我调用writeObject方法时,它应该将对象发送到上面线程的Object输出流。

On the other device, the code is similar. 在另一台设备上,代码类似。 It just listens on the Object input stream for an object, once it has been found it sends a MESSAGE_READ_OBJECT message to my message handler in the main activity: 它只是侦听对象的Object输入流,一旦找到它就会向主活动中的消息处理程序发送MESSAGE_READ_OBJECT消息:

static class MessageHandler extends Handler {
        private final WeakReference<MainActivity> mActivity;

        MessageHandler(MainActivity activity) {
            mActivity = new WeakReference<>(activity);
        }
        @Override
        public void handleMessage(Message msg)
        {
            final MainActivity mainActivity = mActivity.get();
            if (mainActivity == null) {
                return;
            }
            switch(msg.what){

                case Constants.MESSAGE_READ_OBJECT:
                    Object receivedObject = msg.obj;

                    //How should I pull out the hashmap here?

                    switch(type){
                        case "subInfo":
                            //do some things
                            break;
                    }
                    break;
            }
        }
    }

What is the correct way to reassemble the hashmap in my message handler? 在我的消息处理程序中重新组合hashmap的正确方法是什么? I need to check the "type" key of the map and switch based on that, but as of right now I'm not sure how to get the map object back. 我需要检查地图的“类型”键并根据它进行切换,但截至目前我还不确定如何恢复地图对象。 The receivedObject object in my message handler doesn't seem to behave like a hashmap, and doesn't have the typical methods used for pulling out keys and values 我的消息处理程序中的receivedObject对象似乎不像hashmap,并且没有用于提取键和值的典型方法

Furthermore, instead of sending a generic Object over bluetooth, would it make more sense to directly send a Map type object? 此外,不是通过蓝牙发送通用Object ,而是直接发送Map类型对象更有意义吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM