August 13, 2021

Foreground Service in Android

By lj007

Foreground Service

Why foreground Service?

It is important that user must know, what is happening in his device. He should aware about background processes. So, google decide that if you are using any resource in background you must tell user that we are running in background. 
Many users faces issue about background location tracking, and too much data consumption, because they don’t know who is draining battery, who is draining my data. For that it needs to be necessary to display something for every app which works while user not using app.

What is foreground service?

After android O, android introduces foreground service. what it is actually?. It is nothing but your regular service, with sticky notification. Whenever apps want to complete some long task like retrieving new feeds, they must show sticky notification to user. If you don’t do this, android will kill your service without warning and process may interrupt.

How can I convert my service in foreground service?

Is is simple, just create notification channel, In service create notification and write startForeground(ID, notification). Boom, you have converted your service in foreground service. Check here some code:

Create notification channel

  
  private fun createNotificationChannel() {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            val serviceChanngel = NotificationChannel(SERVICE_CHANNEL_ID, "Messaging Service", NotificationManager.IMPORTANCE_DEFAULT)
            val manager = getSystemService(NotificationManager::class.java)
            manager.createNotificationChannel(serviceChanngel)
        }
    }
  
  

make foreground service

  
  override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val notificationIntent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            this,
            0, notificationIntent, 0
        )
        val notification = NotificationCompat.Builder(this, DemoApp.SERVICE_CHANNEL)
            .setContentTitle("Smartechs Demo App")
            .setContentText("")
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pendingIntent)
            .build()

        startForeground(1, notification)
        return START_NOT_STICKY
    }
  
  

Start service

  
  		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    startForegroundService(Intent(this, YalgaarBackgroundService::class.java))
                } else {
                    startService(Intent(this, YalgaarBackgroundService::class.java))
                }
  
  

Conclusion

 It is good to use foreground service, to make sure our background work done completely, and android have not killed our service in between work.