简体   繁体   中英

Is it possible to run service endlessly in android even after closing the app?

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.

Use START_STICKY in the service class

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

and also add this in the manifest:

<service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true"
            android:stopWithTask="false"/>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM