Tuesday 11 April 2017

Android Check Socket Connection Status on Button Click

Hello there I am learning Socket IO to my own and following this link, I just want to learn how to connect to the socket via my url; I am doing it like:

private void connectMe() {
        try {
            IO.Options opts = new IO.Options();
            opts.forceNew = true;
            opts.reconnection = true;
            socket = IO.socket("http://myurl:port",opts);

            socket.connect();
        } catch (Exception exp) {
            Log.e("x1", exp.toString());
        }
    }

I am calling this method from the onCreate Method of my Activity! Then I have a Button and clicking that button I want to check the connection status! I am doing it as:

   but.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                       try{
                           if(socket.connected()==true){
                               Log.e("keyx","Connected");
                           }
                           else{
                               Log.e("keyx","Not Connected");
                           }
                       }catch (Exception exp){
                           Log.e("x1",exp.toString());
                       }
                    }
                });

            } catch (Exception exp) {
                Log.e("x1", exp.toString());
            }
 }

The problem is that I only want to connect through the Socket when my app starts and in on create method I have called the connect to socket method like above in my code!

Now on click of the button I want to check the status! The status I am getting always is the execution of else block each time i click my button after connecting to the Socket.

May be I am getting this as wrong, please try to fix me Thanks in advance. NB: I am new to Socket IO and learning it to my own. Thanks



via Android Nerd

No comments:

Post a Comment