Java – how to establish websocket connection in Android service?

I've been trying to create an Android service, which will allow me to maintain the websocket connection and send some data in time. I create a handler in the service to connect to the websocketclient. But it doesn't connect. The website is running, and I've also tested it. If anyone can help, I'm very grateful

Main activity.java

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BroadcastReceiver receiver=new BroadcastReceiver() {

    @Override
        public void onReceive(Context context, Intent intent) {
            TextView text=(TextView) findViewById(R.id.textView);
            text.setText(intent.getStringExtra("msg"));

        }
    };

    registerReceiver(receiver, new IntentFilter(SocketService.BROADCAST_ACTION));

    }


    // Method to start the service
    public void startService(View view) {
        startService(new Intent(getBaseContext(), SocketService.class));
    }

    // Method to stop the service
    public void stopService(View view) {
        stopService(new Intent(getBaseContext(), SocketService.class));
    }



}

Service implementation

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

import java.util.logging.LogRecord;

public class SocketService extends Service {

    boolean status=false;
    public static final String BROADCAST_ACTION = "com.supun.broadcasttest";
    BroadcastReceiver broadcaster;
    BroadcastReceiver broadreciever;
    Intent intent;
    Handler handler;
    WebSocketClient client;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        intent=new Intent(BROADCAST_ACTION);
        handler=new Handler();

    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
         Toast.makeText(this, "Service Started",Toast.LENGTH_LONG).show();// Let it continue running until it is stopped.
         ////////////////////////////////////////////////////////////////////////////////


        try {
            client = new WebSocketClient(new URI(
                    "ws://xxxxxxx-xxxx.rhcloud.com:8000/browser")) {

                @Override
                 public void onOpen(ServerHandshake handshakedata) {
                    Log.d("1", "open");
                    status = true;

                }

                @Override
                public void onMessage(String message) {


                    Log.d("reply", message);
                    intent.putExtra("msg", message);
                    sendBroadcast(intent);

                }

                @Override
                public void one rror(Exception ex) {
                     // TODO Auto-generated method stub

                }

                @Override
                public void onClose(int code, String reason, boolean remote{
                    status = false;

                }
            };




        }catch(Exception e){


        }
            ///////////////////////////////////////////////////////////////////////////////

//
        handler.removeCallbacks(runnable);
        handler.postDelayed(runnable, 1000);
        return START_STICKY;
    }




    private Runnable runnable=new Runnable() {
        @Override
        public void run() {
            client.connect();

            for(int i=0; i<5;i++){
                if(status){
                    intent.putExtra("msg","open");
                    sendBroadcast(intent);
                    break;
                }else{
                    try {
                        intent.putExtra("msg",client.getReadyState().toString());
                        sendBroadcast(intent);
                        Thread.sleep(1000);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

            if (!status) {
                intent.putExtra("msg","Time Out");
                sendBroadcast(intent);

            }



        }
    };





    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }
}

I'm calling the start service method in the main activity through the button click event. The output always goes to closing quickly and is finally displayed as timed out. I want to know what the possible reason is?

resolvent:

The websocket client you are using is not a powerful attempt to use the engine IO client I used for the project, with excellent performance https://github.com/nkzawa/engine.io-client.java Not all clients are compatible with your server. Check what is being used on the server, and you should use different libraries on the server and client to copy the connection, resulting in disconnection

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>