How to handle socket events as a background service in Android?

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
    // 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;
    }
}
+4
source share
2 answers

, . , .

+3

. , ANR ( ), - . 5 . .
:

  • Thread
  • 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() {
                =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;
        }
    }
    
+3

Source: https://habr.com/ru/post/1660751/


All Articles