android - Web Socket在多个Fragments和Activity中收发数据

标签 android sockets websocket

我是第一次使用 websocket,它是一种 Uber 应用程序。我正在从套接字接收数据,套接字连接和接收器在公共(public)类中,但我很困惑如何以优化的方式为特定 Activity 或 fragment 传递数据。据我所知,我考虑过在必修课中使用广播接收器,但这不是一个好方法......所以任何帮助将不胜感激。

最佳答案

找到了一个很好的解决方案,我不认为它是最终的,但它比 Brad cast receiver 工作得更快。

  1. 我在 Main Activity 中创建了一个接口(interface),其中包含一个发送接收到的数据的方法。

    public class MainActivity extends AppCompatActivity{
    
        SendData sendData;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        public interface SendData {
            public void sendData(String data);
        }
    
    }
    
  2. 在需要主 Activity 响应的 fragment 类中,我实现了主 Activity 的上述接口(interface)。

    public class Storage extends Fragment implements MainActivity.SendData{
    
        View view;
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
            view = inflater.inflate(R.layout.driver_info_fragment,container,false);
            return view;
        }
    
        @Override
        public void SendData(String data) {
           String dataReceived = data;
        }
    
    }
    
  3. 当我在 Main Activity 中收到数据时,我将获得当前 fragment ,如果我想将数据发送到该 fragment ,那么我应该在该 fragment 中实现 Main Activity 接口(interface)并在 Main Class 中创建一个转换当我有数据并用值通知 fragment 时

    public class MainActivity extends AppCompatActivity{
    
        @Override
        public void notifySocketMessage(final String message) {
            if(message != null){
                dataPasser = // define the fragment class name where you need to send the data.
                dataPasser.onDataPass(message); // add the message to the notifier
            }
        }
    
    }
    

关于android - Web Socket在多个Fragments和Activity中收发数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41375154/

相关文章:

authentication - Websocket、Angular 2 和 JSON Web token 身份验证

node.js - Socket.IO TLS 需要 key /证书

python - uwsgi nginx 连接到 unix 套接字被拒绝

java - 使用java从Socket接收字节

java - WebSocket 握手错误 : Unexpected response code: 302

node.js - 如何使用 Web 音频 API 在浏览器上播放 ArrayBuffer 流?

android - 向 Realm 添加新字段后如何设置默认值?

android - 在android中下载图像的想法

java - Android Studio 中的错误 - 一些奇怪的错误

android - 从右到左查看动画android