Android Foreground Services

UkTechians Tutorials
3 min readApr 6, 2021

--

Android Foreground Service is to interact with the user while the service is working in background, User can view the status in Notification Bar the best example to assume what is Foreground Service is when you download any application from Google Play Store and close Google Play Store then you can view notification in status bar that application is download. That’s why we can say Foreground Service instance work’s independently.

Android is working for it user to make android system secure & easy in that way Developer are also working to learn the tips & trick to develop new changes by Google Android.

Let see an example.

Steps to implement Foreground Service:

  • Extend Service
  • Create a Notification mandatory for Android Oreo greater versions
  • Override Method OnStartCommand()
  • Override OnBind()
  • Add Service in Manifest & Permission
  • Start Implementation

Step 1:

Create class ForegroundService extend it with Service and implement method OnBind()

public class ForegroundService extends Service {IBinder binder;@Nullable
@Override
public IBinder onBind(Intent intent) {
return binder;
}
}

Step 2:

Then add method to create notification channel & notification
What is Notification Channel? that will help developer to group notification of an application. Create Channel_id & Channel Name that specify the you appliaction.

Notification Channel or Group.

String Channel_ID = "ServicesInAndroid";
String Channel_Name = "ForeGroundService";
private void notificationChannel(){

if (Build.VERSION.SDK_INT>= 26) {
NotificationChannel notificationChannel = new NotificationChannel(Channel_ID, Channel_Name,
NotificationManager.IMPORTANCE_HIGH);

NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(notificationChannel);
}
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivities(this, 0, new Intent[]{intent}, 0);
Notification notification = new NotificationCompat.Builder(this, Channel_ID)
.setContentTitle("UKTechian Tutorial")
.setContentText("Running Foregroud Service")
.setSmallIcon(R.drawable.logo)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
}

Step 3:

Now override method OnStartCommand() to write the piece of code you want to write or perform action on intent if any.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
notificationChannel();
if (intent.getAction()!=null && intent.getAction().equals("Stop Service")){
stopForeground(true);
stopSelf();
}
return START_STICKY;
}

Full Class View Foreground Service

package com.demo.servicesinandroid;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
public class ForegroundService extends Service {String Channel_ID = "ServicesInAndroid";
String Channel_Name = "ForeGroundService";
IBinder binder;


@Nullable
@Override
public IBinder onBind(Intent intent) {
return binder;
}

private void notificationChannel(){

if (Build.VERSION.SDK_INT>= 26) {
NotificationChannel notificationChannel = new NotificationChannel(Channel_ID, Channel_Name,
NotificationManager.IMPORTANCE_HIGH);

NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(notificationChannel);
}
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivities(this, 0, new Intent[]{intent}, 0);
Notification notification = new NotificationCompat.Builder(this, Channel_ID)
.setContentTitle("UKTechian Tutorial")
.setContentText("Running Foregroud Service")
.setSmallIcon(R.drawable.logo)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
notificationChannel();
if (intent.getAction()!=null && intent.getAction().equals("Stop Service")){
stopForeground(true);
stopSelf();
}
return START_STICKY;
}

@Override
public void onDestroy() {
super.onDestroy();
}
}

Step 4:

Add Foreground Permission in manifest & name of Service in Manifest xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.demo.servicesinandroid">

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

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.ServicesInAndroid">
<activity android:name=".StartForegroundService">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<service android:name=".MediaService"/>
<service android:name=".ForegroundService"
android:exported="false"
android:enabled="true"/>
<activity android:name=".MainActivity"/>
</application>

</manifest>

Step 5:

Create xml file start_foreground_service_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".StartForegroundService">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Service"
android:id="@+id/btn_start_service"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
android:background="@color/purple_200"
android:padding="10dp"
android:layout_margin="20dp"
android:textSize="20sp"
android:textColor="@color/white"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop Service"
android:background="@color/purple_200"
android:id="@+id/btn_stop_service"
android:padding="10dp"
android:layout_margin="20dp"
android:textSize="20sp"
android:textColor="@color/white"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/btn_start_service" />

<ImageView
android:layout_width="140dp"
android:layout_height="140dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:src="@drawable/logo"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Create StartForegroundService to implement Foreground Service.

Now just use startService Builtin method by android to start the service add condition for Android Oreo & greater version startForegroundService as let view full class.

package com.demo.servicesinandroid;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

public class StartForegroundService extends AppCompatActivity {

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

findViewById(R.id.btn_start_service).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(StartForegroundService.this, ForegroundService.class);
if (Build.VERSION.SDK_INT >= 26) {
ContextCompat.startForegroundService(StartForegroundService.this,
intent);
} else {
startService(intent);
}
}
});

findViewById(R.id.btn_stop_service).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(StartForegroundService.this, ForegroundService.class);
intent.setAction("Stop Service");
stopService(intent);
}
});
}
}

To watch full video tutorial click below.

Also follow us on Facebook: https://www.facebook.com/UKTechiansTutorials

--

--

UkTechians Tutorials
0 Followers

UKtechians Tutorials blogs are for those who want to start learning programming languages such as JAVA, Android, Python & more.