How to handle socket events as background service in Android? : <p>I'm new to Android development and I wanted my app to be able to detect socket events even when app is not active via Background service (so I can do push notification e.g if there's a new message triggered by a socket event like how Whatsapp and others do it). </p>

<p>I implemented Background service and an application class that starts the service but stuck where and how to put the socket events as Runnable task in my Background service. </p>

<p>I modified the socket.io android chat project example below and added service and application class.</p>

<p><strong>ChatApplication.java</strong></p>

<pre><code>package com.github.nkzawa.socketio.androidchat;

import android.app.Application;
import android.content.Intent;
import android.content.res.Configuration;

import io.socket.client.IO;
import io.socket.client.Socket;

import java.net.URISyntaxException;

public class ChatApplication extends Application {

    @Override
    // called when the application is starting, before any other application objects have been created
    public void onCreate() {
        super.onCreate();

        // represents our background service
        Intent background = new Intent(this, SocketBackgroundService.class);
        startService(background);
    }

    private Socket mSocket;
    {
        try {
            mSocket = IO.socket(Constants.CHAT_SERVER_URL);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    public Socket getSocket() {
        return mSocket;
    }
}
</code></pre>

<p><strong>SocketBackgroundService.java</strong></p>

<pre><code>package com.github.nkzawa.socketio.androidchat;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class SocketBackgroundService extends Service {
    private boolean isRunning;
    private Thread backgroundThread;

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

    @Override
    public void onCreate() {
        this.isRunning = false;
        this.backgroundThread = new Thread(myTask);
    }

    private Runnable myTask = new Runnable() {
        @Override
        public void run() {
            // do something in here
            Log.i("INFO", "SOCKET BACKGROUND SERVICE IS RUNNING");

            //TODO - how to handle socket events here?
            //How do I do something like mSocket.on(Socket.EVENT_CONNECT,onConnect); here?
        }
    };

    @Override
    public void onDestroy() {
        this.isRunning = false;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if( !this.isRunning) {
            this.isRunning = true;
            this.backgroundThread.start();
        }

        return START_STICKY;
    }
}
</code></pre>
