Android WebSocket Services for Multiple Connections

I created a web socket service. but it supports creating multiple connections

I just want the application to make one connection, unless the network connection drops, and then do another. But right now he is making one connection if I press the home button on the phone. and return to the application, it will make another connection.

Thanks for helping the guys.

onCreate ... of my MainActivity

Intent startServiceIntent = new Intent(this, WebSocketServices.class); startService(startServiceIntent); 

manifest

 <!-- WebSocket --> <receiver android:name="com.example.basicplayerapp.core.NetworkReceiver"> <intent-filter > <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> <service android:name="com.example.basicplayerapp.core.WebSocketServices"></service> 

Networkreceiver

 public class NetworkReceiver extends BroadcastReceiver { public static final String TAG = HomeActivity.class.getSimpleName(); @Override public void onReceive(Context context, Intent intent) { ConnectivityManager conn = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = conn.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) { Log.i(TAG, "connected"); Intent startServiceIntent = new Intent(context, WebSocketServices.class); context.startService(startServiceIntent); } else if(networkInfo != null){ NetworkInfo.DetailedState state = networkInfo.getDetailedState(); Log.i(TAG, state.name()); } else { Log.i(TAG, "lost connection"); } }//end onReceive };//end NetworkReceiver 

WebsocketServices

 public class WebSocketServices extends IntentService { public static final String TAG = WebSocketServices.class.getSimpleName(); private static String SOCKET_ADDR = "http://171.0.0.1:8080"; private String message = null; private WebSocket socket = null; public WebSocketServices() { super("DownloadService"); } @Override protected void onHandleIntent(Intent intent) { Log.i(TAG, "onHandleIntent"); //SOCKET_ADDR = intent.getStringExtra("ip"); if(socket==null || !socket.isOpen() || socket.isPaused()) connectToPASocket(SOCKET_ADDR); Log.d(TAG,"Service Invoke Function"); }//end onHandleIntent //===================================================================================== // Socket connection //===================================================================================== private void connectToPASocket(String SOCKET_ADDR) { Log.i(TAG, "connectToPASocket()"); // Checking if (socket != null && socket.isOpen()) return; // Initiate web socket connection AsyncHttpClient.getDefaultInstance().websocket(SOCKET_ADDR, null, new AsyncHttpClient.WebSocketConnectCallback() { @Override public void onCompleted(Exception ex, WebSocket webSocket) { Log.i(TAG, "onCompleted"); if (ex != null) { Log.i(TAG, "onCompleted > if (ex != null)"); ex.printStackTrace(); return; } socket = webSocket; socket.setStringCallback(new StringCallback() { public void onStringAvailable(String s) { Log.i(TAG, "socket.setStringCallback > onStringAvailable - s => " + s); System.out.println("I got a string: " + s); message = s; }// end onStringAvailable });// end socket.setStringCallback socket.setDataCallback(new DataCallback() { // Find out what this does @Override public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) { Log.i(TAG, "socket.setDataCallback > onDataAvailable | emitter=> " + emitter + " | bb => " + bb); System.out.println("I got some bytes!"); // note that this data has been read bb.recycle(); } });// end webSocket.setDataCallback }// end onCompleted });// end AsyncHttpClient.getDefaultInstance() }// end connectToPASocket }//end WebSocketServices 
+6
source share
4 answers

MrT, I had a similar task.

Do not use intention. Just use the Service. Because, as soon as the intention is fulfilled, it is completed.

After you switch to the Service, what you can do is use a boolean value to check if your service is running like this:

 boolean isSockeStarted = false; @Override public int onStartCommand(Intent intent, int flags, int startId) { ... if (socket == null || !socket.isOpen() || socket.isPaused()) { if (isSockeStarted) { //not started } else { isSockeStarted = true; } } .... 

This means that this service will be launched only once. until you kill him manually.

this worked for me, try and let me know.

+2
source

Try filtering the actions in the onReceive method - something like if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction()))

+2
source

This happened because after you return to the application, onCreate will be called a second time and it will make another connection to the socket. so you can just not start another service if your IntentService is still running, something like this:

onCreate ... of MainActivity

 if(isMyServiceRunning(WebSocketServices.class)){ Intent startServiceIntent = new Intent(this, WebSocketServices.class); startService(startServiceIntent); } 

to find out if your service is running

 private boolean isMyServiceRunning(Class<?> serviceClass) { ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; } 
+2
source

You should use a regular service, not a service of intent. As soon as the completion of the service is completed, it ends. A service can start a background thread that will support a web socket connection until you explicitly kill it; or the OS restores service memory (in which you will need to start it again).

+1
source

Source: https://habr.com/ru/post/983890/


All Articles