简体   繁体   English

如何在片段中共享从套接字接收到的数据?

[英]How to share received data from socket in fragments?

I open a Bluetooth socket in my main activity and receive information from other device.我在我的主要活动中打开一个蓝牙插座并从其他设备接收信息。

As i show in image below i have two fragment in my activity.如下图所示,我的活动中有两个片段。

在此处输入图片说明

How can i use information which receive from socket Bluetooth in both fragments .我如何使用从两个片段中的套接字蓝牙接收的信息。 note : fragment can change and in general i searching for proper way to share received data.注意:片段可能会改变,通常我会寻找正确的方式来共享接收到的数据。 I receive data with handler as below:我使用处理程序接收数据,如下所示:

private final Handler handler = new Handler() {
    @Override
    public void handleMessage(@NonNull Message msg) {
        switch (msg.what) {
            case BluetoothChatService.MessageConstants.MESSAGE_WRITE:
                byte[] writeBuf = (byte[]) msg.obj;
                String writeMessage = new String(writeBuf);
                break;
            case BluetoothChatService.MessageConstants.MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                String readMessage = new String(readBuf, 0, msg.arg1);
                break;
            case BluetoothChatService.MessageConstants.MESSAGE_DEVICE_NAME:
                connectedDeviceName = msg.getData().getString(BluetoothChatService.MessageConstants.DEVICE_NAME);
                Toast.makeText(getApplicationContext(), "Connected to "
                        + connectedDeviceName, Toast.LENGTH_SHORT).show();
                break;
            case BluetoothChatService.MessageConstants.MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(),
                        msg.getData().getString(BluetoothChatService.MessageConstants.TOAST),
                        Toast.LENGTH_SHORT).show();
                break;
        }
        super.handleMessage(msg);
    }
};

You can use offline Databases such as Room .您可以使用离线数据库,例如 Room 。 ( do not forget to execute your queries in the background thread. use executors and thread-pools). (不要忘记在后台线程中执行您的查询。使用执行程序和线程池)。 in addition to this, you also can use intents to transfer data between some fragments.除此之外,您还可以使用意图在某些片段之间传输数据。 finally, I think the best way to share data between fragments(or generally, modules) is to use an architecture having a shared repository such as MVVM, MVC etc. they both use offline DB as repositories.最后,我认为在片段(或一般来说,模块)之间共享数据的最佳方法是使用具有共享存储库的架构,例如 MVVM、MVC 等。它们都使用离线 DB 作为存储库。

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

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