繁体   English   中英

即使应用程序已经销毁,如何使服务在后台运行?

[英]How to make a service that running in the background even if the app's already destroyed?

我想制作一个功能,当我的 firebase 数据库中有数据更改时通知用户。 问题是当应用程序被销毁时,服务会自动销毁。 之后,当数据库中的数据发生变化时,我的应用程序不会通知用户。

这是我的应用程序的一些片段代码。

服务 :

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG, "DogNotificationService created")

        val phone = intent?.extras?.getString("PHONE")

        if(isFirstTime) {
            val firebaseDatabase = FirebaseDatabase.getInstance()

            notificationReference = firebaseDatabase.getReference("walker/$phone/notification")

            val coroutineScope = CoroutineScope(Job() + Dispatchers.IO)

            coroutineScope.launch {
                launchListener()
            }

            isFirstTime = false
        }

        return super.onStartCommand(intent, flags, startId)
    }

    fun launchListener() {
        valueEventListener =
            notificationReference.addValueEventListener(object : ValueEventListener {
                override fun onCancelled(p0: DatabaseError) {
                    Log.w(TAG, "Read failed: " + p0.message)
                }

                override fun onDataChange(p0: DataSnapshot) {
                    val notificationData = p0.getValue(String::class.java)

                    if(count > 0) {
                        Log.d(TAG, notificationData)
                        sendNotification(notificationData!!)
                    }

                    count++
                }

            })
    }

当我启动服务时:

private fun startNotificationService() {
        val intent = Intent(context, DogNotificationService::class.java)
        intent.putExtra("PHONE", "081293312313")

        Log.d(TAG, "Start notification service")

        activity?.startService(intent)
    }

如果有任何想法来做这种方法,请帮忙。

我在一个应用程序中工作以跟踪用户以允许他们记录他们的轨迹,并发现如果 android 系统需要可用内存,则可以随时终止服务。 即使您的服务有唤醒锁或在前台运行。

我找到的解决方案是将 警报与前台服务一起使用,如果您安排警报,无论您的应用程序是否仍在执行,都会触发此警报。 这样,即使系统由于缺乏资源而终止了应用程序,我的应用程序也可以获得设备位置。 这是我发现在这种情况下有效的唯一解决方案。 唤醒服务的闹钟。

这个想法是在一些 google i/o 中想到的,当时他们说如果你真的需要你的应用程序继续,无论你应该使用警报而不是服务。

除此之外,如果您需要不断唤醒应用程序,那么使用exact警报作为某些设备中的inexact警报,如果它们应该被触发的时间太接近当前时间,它们可能会在 5 分钟后被触发。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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