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).
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.
I modified the socket.io android chat project example below and added service and application class.
ChatApplication.java
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;
}
}
SocketBackgroundService.java
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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With