WebSocket with Service每次启动时都会创建新的Connection

时间:2018-04-01 10:46:56

标签: android websocket android-service java-websocket android-service-binding

我是初学者,使用service和webSocket。

我正在尝试使用Android中的服务连接并在webSocket上发送String,但是当调用StartService()时,它每次都会给我一个新的连接。我需要每次都发送文本字符串而不创建新连接。

我使用的代码如下

library(plotly)
library(purrr)

# using purrr::map
mtcars %>% 
  split(mtcars$cyl) %>% 
  map(~{
    plot_ly(data = .x, 
            x = rownames(.x), 
            y = .x$mpg, 
            type = "bar")
  }) %>% 
  subplot(margin = .05)

# using lapply
mtcars %>% 
  split(mtcars$cyl) %>% 
  lapply(function(x) {
    plot_ly(data = x, 
            x = rownames(x), 
            y = ~mpg, 
            type = "bar")
  }) %>% 
  subplot(margin = .05)

ActivityClass

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();
}

0 个答案:

没有答案