簡體   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