Suresh Sharma
Suresh Sharma

Reputation: 57

Socket.io client on android disconnecting after 5 minutes

I have implemented Socket.io client on android, I have managed to initialize the socket in an Unbounded service but the problem is it got disconnected after 5 minutes when the app is in background and phone is locked. If the app is in foreground the connection remains alive endless.

Situation on Disconnection:

  1. Service is still Running
  2. Socket is disconnected due to unknown reason
  3. Socket instance is create in Singelton class and the instance remain same always in the lifecycle, i have checked the hashcode for socket instance.
  4. I have implemented the Ping Pong solution as well but it is not working.
  5. Checked the server logs and found the socket is disconnected for the user.
  6. I have even tried to restart the service but didn't got connect after restart.
  7. The only way to connect the socket again to kill the app and restart the app.

MySingelton.java

public class Singelton implements Serializable {
    private static Singelton instance;
    private static final String SERVER_ADDRESS = "xyz";
    private Socket mSocket;
    private Context context;

    public Singelton(Context context) {
        this.context = context;
        this.mSocket = getServerSocket();
    }

    public static Singelton get(Context context){
        if(instance == null){
            instance = getSync(context);
        }
        instance.context = context;
        return instance;
    }

    private static synchronized Singelton getSync(Context context) {
        if(instance == null){
            instance = new Singelton(context);
        }
        return instance;
    }

    public Socket getSocket(){
        return this.mSocket;
    }

    public Socket getServerSocket() {
        try {
            IO.Options opts = new IO.Options();
            opts.forceNew = true;
            opts.reconnection = true;
            mSocket = IO.socket(SERVER_ADDRESS, opts);
            return mSocket;
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }
}

MyService

public class MessageService extends Service {
    Socket mSocket;
    
    public MessageService() {
        mSocket = Singelton.get(this).getSocket();
        Log.d("chat", "Constructor"+String.valueOf(mSocket.hashCode()));
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("chat", "onStartCommand"+String.valueOf(mSocket.hashCode()));
        initSocket();
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
        wl.acquire();
        //Log.e(TAG, "onStartCommand");
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        Log.d("chat", "onDestroyed");
        Calendar cal = Calendar.getInstance();
        Intent intent = new Intent(getApplicationContext(), MessageService.class);
        PendingIntent pintent = PendingIntent.getService(MessageService.this, 0, intent, 0);
        AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+(1*1000), pintent);

        super.onDestroy();
    }

    @Override
    public void onCreate() {
        Log.d("chat", "onCreate");
        super.onCreate();
    }

    private void initSocket(){
        mSocket.on(Socket.EVENT_CONNECT,onConnect);
        mSocket.on(Socket.EVENT_DISCONNECT,onDisconnect);
        mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
        mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
        mSocket.on(Socket.EVENT_RECONNECT, onReconnect);
        mSocket.on("pingy", ping);      
        mSocket.connect();
        mSocket.emit("pongy", "Hi");
    }
    int i=0;
    Emitter.Listener ping = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Log.d("chat", String.valueOf(i) + " " + mSocket.hashCode());
            i++;
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    new CountDownTimer(2000,1000) {
                        @Override
                        public void onTick(long millisUntilFinished) {

                        }

                        @Override
                        public void onFinish() {
                            mSocket.emit("pongy", "Hi");                           
                        }
                    }.start();
                }
            });
        }
    };

    Emitter.Listener onConnect = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Log.d("chat", "connected");
        }
    };
    Emitter.Listener onReconnect = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Log.d("chat", "onReconnect");
        }
    };
    Emitter.Listener onDisconnect = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            //mSocket.disconnect();
            Log.d("chat", "onDisconnect");
            stopSelf();
        }
    };
    Emitter.Listener onConnectError = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Log.d("chat", args[0].toString());
        }
    };
    
    
    
    
    
    

    

    

 
}

Note: I want to make the service running in the background all the time and it should not be killed by the system or with the app

Upvotes: 0

Views: 2290

Answers (0)

Related Questions