I am new to Android development, and I wanted my application to detect socket events even when the application is not active through the Background service (so that I can give a push notification, for example, if there is a new message caused by a socket event like Whatsapp and others do this).
I implemented a background service and an application class that starts the service, but stuck where and how to put socket events as a Runnable task in my background service.
I modified the socket.io android chat sample project below and added a 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
public void onCreate() {
super.onCreate();
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() {
Log.i("INFO", "SOCKET BACKGROUND SERVICE IS RUNNING");
}
};
@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;
}
}
source
share