Android Websocket Services Making Multiple Connections
Solution 1:
MrT, I had a similar probelm.
Dont use intentService. Just use Service. Because once the intentService has been done, it will finish itself.
After you change to Service, What you can do, is to use boolean to check if your service has been started like so:
booleanisSockeStarted=false;
@OverridepublicintonStartCommand(Intent intent, int flags, int startId) {
...
if (socket == null || !socket.isOpen() || socket.isPaused()) {
if (isSockeStarted) { //not started
} else {
isSockeStarted = true;
}
}
....
That mean, this service will only start once. until you kill it manually.
it worked for me, try and let me know.
Solution 2:
Try filtering the actions in onReceive Method - something like
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction()))
Solution 3:
It happened because after your returning to app onCreate will be call for second time and it make another connection to socket . so you can simple don't start another service if your IntentService is still running , something like this :
onCreate... of MainActivity
if(isMyServiceRunning(WebSocketServices.class)){
Intent startServiceIntent = newIntent(this, WebSocketServices.class);
startService(startServiceIntent);
}
method to see if your service is running
privatebooleanisMyServiceRunning(Class<?> serviceClass) {
ActivityManagermanager= (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
returntrue;
}
}
returnfalse;
}
Solution 4:
You should use a regular service, not an intent service. Once intent service is finished, it finishes. A service can start a background thread that will maintain the web socket connection until you explicitly kill it; or the OS reclaims the service's memory (in which you'd need to start it again).
Post a Comment for "Android Websocket Services Making Multiple Connections"