gpt4 book ai didi

java - Android - Service、IntentService、JobIntentService - 如果应用程序被杀死,它们就会停止

转载 作者:IT老高 更新时间:2023-10-28 13:45:28 25 4
gpt4 key购买 nike

我已经在 StackOverflow 和 Web 中阅读了许多相同的问题,但即使从任务中删除应用程序(强制终止),也无法配置“永无止境的服务”或运行之类的内容。我只是想知道像 Viber 或 WhatsUp 这样的服务是如何工作的,因为当我们强制终止这些应用程序时,当有人写信给我们时,我们仍然能够接收消息(所以服务仍在运行)。我知道前台服务,但这不是解决方案,因为用户不想看到通知。所以这里是我尝试过的。 :此代码在服务内部运行以检测实时更改,只是希望它在应用程序的每个条件下保持活跃:前景、背景、已删除等...

firestoreDb!!.collection("example").document("example").collection("real_time_request")
.addSnapshotListener { documentSnapshot: QuerySnapshot?, _: FirebaseFirestoreException? ->

}

当用户的集合发生变化时,我正在使用这样的服务从 Firestore 数据库获取实时数据。

我尝试服务的方式是:

FirestoreListeners : IntentService("Firestore Listeners")
FirestoreListeners : Service
FirestoreListeners : JobIntentService

当应用程序处于前台或后台时,上述一切工作正常,但在应用程序被强制关闭后服务被终止(从任务中删除时)

我已尝试在 list 中进行此更改:

android:stopWithTask="false"
android:directBootAware="true"
android:process=":remote"

在应用程序层次结构中:

android:persistent="true"

在 IntentService onHandleIntent 中:

setIntentRedelivery(true)

在服务 onStartCommand :

return START_STICKY

如果系统破坏或杀死它,尝试重新启动服务:

override fun onTaskRemoved(rootIntent: Intent) {
val restartServiceIntent = Intent(applicationContext, this::class.java)
restartServiceIntent.setPackage(packageName)
val restartServicePendingIntent = PendingIntent.getService(applicationContext, 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT)
val alarmService = applicationContext.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePendingIntent)
Log.e("Service Firestore ", "Task Removed")
super.onTaskRemoved(rootIntent)
}

但没有什么可以正常工作。实现这一目标的最佳解决方案是什么?因此,目的是让某些东西在后台运行并监听 Firestore 更改(或其他东西),即使在应用程序被杀死或从任务中删除之后,比如 Viber 等......也许他们正在使用没有通知图标的前台服务?但我不认为Android允许我们做这种前台服务(没有通知)

我已经阅读了一些关于 WorkManager 的文章,正如 Google 所说:

Note: WorkManager is intended for tasks that require a guarantee that the system will run them even if the app exits, like uploading app data to a server. It is not intended for in-process background work that can safely be terminated if the app process goes away; for situations like that, we recommend using ThreadPools.

但无法弄清楚它是如何工作的或如何用于我的目的

谢谢

最佳答案

当您的应用处于未运行/前台时,您可以使用 FCM 推送通知来唤醒设备。当应用收到推送通知时,您可以启动您的服务来执行所需的任务。同样,当应用程序处于后台时,您可能无法启动服务,因为您可能需要将服务作为前台服务运行。

关于java - Android - Service、IntentService、JobIntentService - 如果应用程序被杀死,它们就会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53873643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com