简体   繁体   中英

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

I want to make a feature to notify user when there's data changes in my firebase database. The problem is when the app is destroyed, then the service automatically destroyed. After that when the data in database change, my app won't notify the user.

Here's some snippet code for my apps.

Service :

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++
                }

            })
    }

When I start the service :

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

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

        activity?.startService(intent)
    }

If any idea to do this approach, please help.

I was working in an app to keep track of the users to allow them record their tracks and found out that services can be killed at any moment if the android system requires free memory. Even if your service haswakelocks or is running in foreground.

The solution I found was to use alarms with a foreground service, if you schedule alarms this alarms will be fired whether your app is still executing or not. That way my app could get the device position even though the system had killed the app due to lack of resources. It's the only solution I found that works in this scenario. An alarm that wakes up the service.

The idea came to me in some google i/o when they said that if you really need your app to continue no matter what you should use alarms instead of services.

Besides that, if you need the app to be awaked constantly then use exact alarms as the inexact ones in some devices they might be fired 5 minutes later if the time that they should be fired is too near to the current time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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