How to handle socket events as background service in Android?

You open socket on main thread. Do not open socket connections on main thread, it will gives you ANR(application not responding) error which is occur due to lots of heavy work on UI thread. It blocks UI thread for more than 5 sec. So I suggest you to open socket connections on thread inside service.
Here is example using plain socket:

  1. Create one service class for starting thread on background service
  2. Create on Thread class for opening socket connection on thread
  3. create separate class for socket communication

    public class SocketBackgroundService extends Service {
    
    private SocketThread mSocketThread;
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    @Override
    public void onCreate() {
    
        mSocketThread = SocketThread.getInstance();
    }
    
    
    @Override
    public void onDestroy() {
        //stop thread and socket connection here
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (mSocketThread.startThread) {
        } else {
            stopSelf();
        }
    
        return START_STICKY;
    }
    }
    
    public class SocketThread extends Thread {
    
    private static SocketThread mSocketThread;
    private SocketClient mSocketClient;
    
    private SocketThread() {
    }
    
    // create single instance of socket thread class
    public static SocketThread getInstance() {
        if (mSocketThread == null)//you can use synchronized also
        {
            mSocketThread = new SocketThread();
        }
        return mSocketThread;
    }
    
    
    public boolean startThread() {
          mSocketClient = new SocketClient();
        if (socketClient.isConnected()) {
            mSocketThread.start()
            return true;
        }
        return false;
    }
    
    @Override
    public void run() {
        super.run();
        while (mSocketClient.isConnected()) {
            // continue listen
        }
        // otherwise remove socketClient instance and stop thread
    }
    
    public class SocketClient {
        //write all code here regarding opening, closing sockets
        //create constructor
        public SocketClient() {
            // open socket connection here
        }
    
        public boolean isConnected() {
            return true;
        }
    }
    

If you need the socket to be alive even after your application is stopped. Move your socket to the Background service and then you can add the socket events in the service.