[英]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.我试过警报管理器在预定的时间给我通知,但如果我想继续订阅我的服务器上的某个主题,通过关闭应用程序,连接将关闭,我能做些什么来保持与我的服务器的连接,使用web 套接字或后台服务。 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在服务 class 中使用
START_STICKY
@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
使用WorkManager来调度任务,尤其是
OneTime
Worker will still "running" event if the app is killed.如果应用程序被终止,工作人员仍将“运行”事件。
You could do something like that.你可以做那样的事情。
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.工作人员只需要处理通知触发器。
Now create a OneTimeWorkRequest
because you only need to trigger the notification once.现在创建一个
OneTimeWorkRequest
,因为您只需要触发一次通知。
Alternatively, you could use a PeriodicWorkRequest
for recurring work.或者,您可以使用
PeriodicWorkRequest
进行重复性工作。
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 将其排队到系统的活动任务列表中:
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.此时,WorkManager 会将工作添加到其队列中,然后确定何时可以运行并按照第一步指定的方式执行工作。 And there you go, your notifications will now trigger on time, regardless of device restarts , app force closes , and without using a bulky service.
go,你的通知现在会准时触发,无论设备重启、应用强制关闭,也无需使用庞大的服务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.