Foreground Service Android

Foreground Service Android Example

In this post, we will learn about foreground service android, How does work? What are the advantages and implementation?. So let’s get started.

Before to start with Foreground Service please refer Notification 

What is Foreground Service?

The foreground service always uses the notification to notify the user and using the notification you can actually interact with the service or the ongoing operation such as pause the music or play the next music.

So whenever in your app you see a notification that is performing some long running tasks that service is basically the foreground service and Foreground Service is always noticeable to the user that is the user is aware of this ongoing process

Example

Step 1: Create Android Project

Step 2: Create ForgroundService class which extends Service class.

package com.rrtutors.androidsamples.services

import android.app.Service
import android.content.Intent
import android.app.PendingIntent
import android.os.IBinder
import com.rrtutors.androidsamples.MainActivity
import androidx.core.app.NotificationCompat
import com.rrtutors.androidsamples.R
import android.app.NotificationManager
import android.app.NotificationChannel
import android.os.Build
import android.content.Context
import android.graphics.Color


class ForgroundService: Service() {
    val CHANNEL_ID = "ForegroundServiceChannel"
    var serviceChannel: NotificationChannel? =null;
    var manager:NotificationManager?=null;
    override fun onCreate() {
        super.onCreate()
    }
    override fun onBind(intent: Intent?): IBinder? {
        return null;
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val input = intent?.getStringExtra("inputExtra")
        createNotificationChannel()
        val notificationIntent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            this,
            0, notificationIntent, 0
        )
        manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            serviceChannel?.let { manager!!.createNotificationChannel(it) }
        }

        val notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(android.R.drawable.ic_notification_clear_all)
            .setContentTitle("Foreground Service")
            .setContentText(input)
            .setContentIntent(pendingIntent)
            .build()
        //manager?.notify(1,notification)
        startForeground(1, notification)
        //do heavy work on a background thread
        //stopSelf();
        return Service.START_NOT_STICKY

    }


    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelId = "some_channel_id"
            val channelName = "Some Channel"
            val importance = NotificationManager.IMPORTANCE_LOW
            serviceChannel = NotificationChannel(channelId, channelName, importance)
            serviceChannel?.enableLights(true)
            serviceChannel?.lightColor = Color.RED
            serviceChannel?.enableVibration(true)
            serviceChannel?.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
}
    }
}

Step 3: Create Notification Channel

Notification Channels provide us with the ability to group the notifications that our application sends into manageable groups. Once our notifications are in these channels, we no longer have input into their functionality — so it is up to the user to manage these channels

We now have access to a method called createNotificationChannel() from the Notification manager. We can use this to create channels for our application notifications

private fun createNotificationChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channelId = "some_channel_id"
        val channelName = "Some Channel"
        val importance = NotificationManager.IMPORTANCE_LOW
        serviceChannel = NotificationChannel(channelId, channelName, importance)
        serviceChannel?.enableLights(true)
        serviceChannel?.lightColor = Color.RED
        serviceChannel?.enableVibration(true)
        serviceChannel?.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
 }
}

 

Step 4: Update Manifestfile

Declare your service in manifest file with below code inside application tag

<service
        android:name=".services.ForgroundService"
        android:enabled="true"
        android:exported="true"/>

 

add uses permision to run foreground service 

<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

Step 5: Update xml file

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".services.ForegroundServiceActivity">
    <Button
            android:id="@+id/buttonStartService"
            android:layout_marginStart="8dp"
            android:layout_marginEnd="8dp"
            android:background="#F10956"
            android:layout_width="120dp"
            android:gravity="center"
            android:textSize="16sp"
            android:layout_height="35dp"
            android:text="Start Service"
            android:textColor="#fff"
            app:layout_constraintBottom_toTopOf="@+id/buttonStopService"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_chainStyle="packed" />
    <Button
            android:id="@+id/buttonStopService"
            android:layout_width="120dp"
            android:gravity="center"
            android:textSize="16sp"
            android:layout_height="35dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="24dp"
            android:layout_marginEnd="8dp"
            android:layout_marginBottom="8dp"
            android:background="#F10956"

            android:text="Stop Service"
            android:textColor="#fff"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/buttonStartService"/>

</androidx.constraintlayout.widget.ConstraintLayout>

 

Step 6: Update activity class

package com.rrtutors.androidsamples.services

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import com.rrtutors.androidsamples.R
import kotlinx.android.synthetic.main.activity_forground.*
import android.content.Intent
import androidx.core.content.ContextCompat

class ForgroundActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(com.rrtutors.androidsamples.R.layout.activity_forground)

        buttonStartService.setOnClickListener( View.OnClickListener {
            startService();
        })
        buttonStopService.setOnClickListener( View.OnClickListener {
            stopService();
        })
    }

    fun startService() {
        val serviceIntent = Intent(this, ForgroundService::class.java)
        serviceIntent.putExtra("inputExtra", "Foreground Service Example in Android")
        ContextCompat.startForegroundService(this, serviceIntent)
    }

    fun stopService() {
        val serviceIntent = Intent(this, ForgroundService::class.java)
        stopService(serviceIntent)
    }
}

 

Step 7: Run application

Android Foreground service

Android Foreground Service