Home > Software design >  Is it possible to run service endlessly in android even after closing the app?
Is it possible to run service endlessly in android even after closing the app?

Time:02-24

I tried alarm manager to give me notification on a scheduled time but if I want to stay subscribed to my server on a topic, by closing the app, connection will be closed, is there anything I can do to stay connected to my server, using web socket or background services. I've tried background service, but that too stops after sometime when app is closed, nothing happens to stay alive.

CodePudding user response:

Use the WorkManager for scheduling task, especially the OneTime

Worker will still "running" event if the app is killed.

You could do something like that.

  1. Building the Worker Class
import android.content.Context
import androidx.work.Worker
import androidx.work.WorkerParameters

class NotifyWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {

    override fun doWork(): Result {
        // Method to trigger an instant notification
        triggerNotification()

        return Result.success()
    }
}

The worker only need to handle the notification trigger.

  1. Building the Work Request

Now create a OneTimeWorkRequest because you only need to trigger the notification once.

Alternatively, you could use a PeriodicWorkRequest for recurring work.

        val notificationWork = OneTimeWorkRequest.Builder(NotifyWorker::class.java)
            .setInitialDelay(delay) // this is when your notification should be triggered 
            .setInputData(inputData) // this is the data you can pass to the NotifyWorker 
            .addTag("notificationWork")
            .build()

Now that you have created everything you need to schedule the work, you can just ask the WorkManager to queue it to the list of active tasks from the system:

  WorkManager.getInstance(context).enqueue(notificationWork)

At this point, the WorkManager will add the work to its queue, then determine when it can run and do the work as specified in the first step. And there you go, your notifications will now trigger on time, regardless of device restarts, app force closes, and without using a bulky service.

CodePudding user response:

Use "START_STICKY" in service class

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }
  • Related