简体   繁体   中英

Connect to websocket in activity A and recieve data in activity B

I have an fragment A in which i am making an websocket connection and after successful connection it will open another fragment B, now in this fragment i want to recieve data from that created websocket connection and just display data in a textview. I am determining the success of websocket by getting a flag in a string from server. It is working fine. Now the websocket is connection is successful and it is opening another fragment. But in new new fragment its not recieveing data from server. How can i do it and please help me with some code as i am new to websocket.

In short, Fragment A is working file, I want to know what to do in fragment B to recieve data from the connection created in Fragment A. The code i have written in fragment B is just by assumption

Fragment A

//calling start in a button click

private void start(String ip, String dev_pass) {
        String URL = "some URL";
            Request request = new Request.Builder().url(URL).build();
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("key",dev_pass);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            CustomWebSocketListener listener = new 
            CustomWebSocketListener(jsonObject);
            WebSocket ws = client.newWebSocket(request, listener);
        }
    }

private final class CustomWebSocketListener extends WebSocketListener {
        private static final int NORMAL_CLOSURE_STATUS = 1000;
        JSONObject credintials;
        public CustomWebSocketListener(JSONObject credintials) {
            this.credintials = credintials;
        }
        @Override
        public void onOpen(final WebSocket webSocket, Response response) {        
            webSocket.send(String.valueOf(credintials));

        }
        @Override
        public void onMessage(WebSocket webSocket, String text) {
            output(text);
        }
        @Override
        public void onMessage(WebSocket webSocket, ByteString bytes) {
            output(text);
        }
        @Override
        public void onClosing(WebSocket webSocket, int code, String reason) {
            webSocket.close(NORMAL_CLOSURE_STATUS, null);
        }
        @Override
        public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        }
    }
  private void output(final String text) {
        String err_code = "";
        try {
            JSONObject jsonObject = new JSONObject(text);
            err_code = jsonObject.getString("err_code");
            if (err_code.equalsIgnoreCase("0")) {
                // here open fragment B as the error is 0 and 
                // that means the connection is successful 
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new BFragment()).commit();
            } else {
                // do something if json errorcode is 1
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Fragment B


in OnCreate()  ------
String URL = "SAME URL";
Request request = new Request.Builder().url(URL).build();
        CustomWebSocketListener listener = new CustomWebSocketListener();
        WebSocket ws = client.newWebSocket(request, listener);
------

    private final class CustomWebSocketListener extends WebSocketListener {
        private static final int NORMAL_CLOSURE_STATUS = 1000;
        public CustomWebSocketListener() {

        }
        @Override
        public void onOpen(final WebSocket webSocket, Response response) {
           // not doing anything as already conneted
           // i dont know if this approach is right or wrong 
        }
        @Override
        public void onMessage(WebSocket webSocket, String text) { 
        Toast.makeText(getActivity(), text,
                    Toast.LENGTH_LONG).show();
        }
        @Override
        public void onMessage(WebSocket webSocket, ByteString bytes) {

        }
        @Override
        public void onClosing(WebSocket webSocket, int code, String reason) {
            webSocket.close(NORMAL_CLOSURE_STATUS, null);
            Toast.makeText(getActivity(), "Closing",
                    Toast.LENGTH_LONG).show();
        }
        @Override
        public void onFailure(WebSocket webSocket, Throwable t, Response response) {
            Toast.makeText(getActivity(), "Fail",
                    Toast.LENGTH_LONG).show();
        }
    }

Create a Singleton class for socket operations. In this way, you can access socket class from anywhere and can register for callbacks in any class.

If you wish to pass data from one fragment to another fragment on just store the value to a field variable of Activity and then get the value of that field variable from fragment B

in MainActiviy.java add this

private String data = "";

public String getData(){
       return this.data;
}

public void setData(String data)
{
        this.data += data;
}

in Fragment A when you receive something

 getActivity().setData("message from server....");

in Fragment B

 String data = getActivity().getData();
 // Now update the view text using this String data

Note : Fragment A and Fragment B must be on the same Activity.

I do not know whether its an efficient solution or not. Still it would work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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