0

I am beginner with using service and webSocket.

I am trying to connect and send String on webSocket using Service in Android but when calling StartService(), it gives me anew Connection every time.I need to send text string every time without creating a New Connection.

The code I used is as follows

public class SocketServices extends Service {

    DataOutputStream toServer = null;
    DataInputStream fromServer = null;
    String line = null;

    char frmSe;
    WebSocketClient webSocketClient;
    OutputStream os;
    static Socket socket;
    String message = null;
    public static final String NOTIFICATION = "MyService";
    public static final String TAG = "SOCKETS";
    URI uri;
    static final int MSG_SAY_HELLO = 1;
    private static final String MESSENGER = "MESSENGER";
    boolean isWebSocketConnect = false;

    private static final String PATHNAME = "PATHNAME";

    /**
    * Looper associated with the HandlerThread.
    */
    private volatile Looper mServiceLooper;
    private ServiceHandler mServiceHandler;

    /**
    * Factory method to make the desired Intent.
    */


    public static Intent makeIntent(Context context, String url, Handler downloadHandler) {
        return new Intent(context,
        SocketServices.class
        .putExtra("js",url)
        .putExtra(MESSENGER,
        new Messenger(downloadHandler));
    }

    public SocketServices() {

    }

    @Override
    public void onCreate() {
        super.onCreate();
        // Create and start a background HandlerThread since by
        // default a Service runs in the UI Thread, which we don't
        // want to block.
        try {
            uri = new URI("ws://localhost:port");

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

        }
        HandlerThread thread =
        new HandlerThread("DownloadService");
        thread.start();

        // Get the HandlerThread's Looper and use it for our Handler.
        mServiceLooper = thread.getLooper();
        if(isWebSocketConnect == false){
            mServiceHandler =
            new ServiceHandler(mServiceLooper);}
            else {
                isWebSocketConnect=true;
            }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        Message message = mServiceHandler.makeDownloadMessage(intent);

        // Send the Message to ServiceHandler to retrieve an image
        // based on contents of the Intent.
        mServiceHandler.sendMessage(message);

        return START_STICKY;
    }

    // here use class handeller With Messenger to connect with activity and do process

    private final class ServiceHandler extends Handler {
        /**
        * Class constructor initializes the Looper.
        *
        * @param looper
        *            The Looper that we borrow from HandlerThread.
        */
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        private Message makeDownloadMessage(Intent intent) {
            Message message = Message.obtain();
            message.obj = intent;
            return message;
        }

        public void handleMessage(Message message) {
            // Get the intent from the message.
            Intent intent = (Intent) message.obj;

            webSocket(intent);
        }
    }

// method to connect  with web Socket

public void webSocket(final Intent intent) {

    final String request = intent.getStringExtra("jss");

    webSocketClient = new WebSocketClient(uri) {
        @Override
        public void onOpen(ServerHandshake handshakedata) {
            send(request);

        }

        @Override
        public void onMessage(String message) {
            sendPath(intent, message);

        }

        @Override
        public void onClose(int code, String reason, boolean remote) {
        }

        @Override
        public void onError(Exception ex) {
            //  System.err.println("an error occurred:" + ex)
        }
    };
    webSocketClient.connect();
}

ActivityClass

Intent intent= SocketServices.makeIntent(MainActivity.this,String.valueOf(object),mDownloadHandler);

try {
    startService(intent);   
} catch(Exception e) {
    e.printStackTrace();
}
udit7395
  • 626
  • 5
  • 16
  • Do not startService again instead bind your activity with your service. Have a look at this to how to bind you service [Bind service to activity in Android](https://stackoverflow.com/questions/1916253/bind-service-to-activity-in-android). Once you activity is binded with the service you invoke the service methods from your activity – udit7395 Apr 01 '18 at 11:08
  • @udit7395 it give same problem – mohammedragabmohammedborik Apr 01 '18 at 14:59

0 Answers0