![](/img/trans.png)
[英]Restart the service even if app is force-stopped and Keep running service in background even after closing the app How?
[英]Is it possible to run service endlessly in android even after closing the app?
我試過警報管理器在預定的時間給我通知,但如果我想繼續訂閱我的服務器上的某個主題,通過關閉應用程序,連接將關閉,我能做些什么來保持與我的服務器的連接,使用web 套接字或后台服務。 我已經嘗試過后台服務,但是當應用程序關閉一段時間后它也會停止,沒有任何事情可以保持活力。
在服務 class 中使用START_STICKY
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
並將其添加到清單中:
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"
android:stopWithTask="false"/>
使用WorkManager來調度任務,尤其是OneTime
如果應用程序被終止,工作人員仍將“運行”事件。
你可以做那樣的事情。
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()
}
}
工作人員只需要處理通知觸發器。
現在創建一個OneTimeWorkRequest
,因為您只需要觸發一次通知。
或者,您可以使用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()
現在您已經創建了安排工作所需的一切,您可以要求 WorkManager 將其排隊到系統的活動任務列表中:
WorkManager.getInstance(context).enqueue(notificationWork)
此時,WorkManager 會將工作添加到其隊列中,然后確定何時可以運行並按照第一步指定的方式執行工作。 go,你的通知現在會准時觸發,無論設備重啟、應用強制關閉,也無需使用龐大的服務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.