Search code examples
androidservicebackground-processandroid-binder

Service running in the background


What I want to achieve is to create a Service(?) which starts/gets registered once Application gets installed and keeps monitor items stored in Array. These items are products with expiry dates so if today is the day of expiry I want to show a notification about it no matter if application is currently running or not.

I have already searched internet and Android developers website for an answer and here is what I learned:

  1. I need to create a Service which in onStartCommand return "START_STICKY" and specify in my android Manifest.xml file that Activity is in SingleTop start mode.
  2. I need to bind this Service with my Activity to pass data in one way or another.

What I don't know how to do is:

  1. Where to start the Service so there is only 1 instance of it?
  2. How to check expiry dates stored in an Array (in Service or Activity) for example once a day?
  3. Array with products, should it be static so it can be accessed either from Activity and Service or I should create separate instance of it and pass data accordingly via Binder?

Generally, I know the basics and how it should work but I lack a concept how to implement it so it will be effective.

Thanks for all answers! :)

// EDIT

Some code of my custom Service as for now:

class ExpiryMonitorService : Service() {

private val productsArray: ArrayList<ProductEntry> = ArrayList()

// Binder which will be given to clients
private val mBinder: IBinder = LocalBinder()

inner class LocalBinder : Binder() {

    fun getService() : ExpiryMonitorService {

        // Return this instance of ExpiryMonitorService so clients can call public methods
        return this@ExpiryMonitorService

    }
}

override fun onBind(intent: Intent?): IBinder {

    return mBinder
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    return START_STICKY // Restart this service if it gets killed by the system
}


}

Solution

  • The answer isn't a service. Its an AlarmManager (or JobScheduler) set to the expiration of the closes to expiration item, and a database of items and expiration dates. When the job goes off, it sends the notification and schedules the next alarm/job based on the data in the db.

    Service isn't the answer because a service can be killed at any time for resources. In addition, on modern versions of Android a Service has limits to how much background processing it can do before being killed. Neither of these makes for a good monitoring solution. Luckily you don't actually need monitoring, you just need to be alerted at a certain time, which is perfect for an alarm.