WebSocket с сервисом создает новое соединение каждый раз, когда startService
Я начинающий с использованием сервиса и webSocket.
Я пытаюсь подключиться и отправить String на webSocket с помощью Service в Android, но при вызове StartService() он каждый раз дает мне новое соединение. Мне нужно каждый раз отправлять текстовую строку без создания нового соединения.
Код, который я использовал, выглядит следующим образом
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();
}