Tag

Service

Browsing

In this tutorial, I will explain about foreground service android, How does work? What are the advantages and implementation? At last, I will prepare a foreground service sample app. So let’s get started.

What is Foreground Service

For more clarity let’s takes example Gmail, You are just using Gmail app and listening to music that is being played by Music Player application. So Music Player is basically using the foreground service to play the music. 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.

Step up to writing implementation

  • Initial Project Setup
  • Create a subclass of Service – ForgroundService.java
  • Create Notification Channel
  • Override methods
    • onStartCommand
      • Mandatory to override for Foreground Service
    • onBind
      • Mandatory to override for Foreground Service
      • Must return null for Foreground Service
    • onCreate
      • Optional to override
      • Call only once, when Service is being created for the first time
    • onDestory
      • Optional to override
      • Call when background service is destroyed
  • Declare your service in Manifest.xml

Foreground Service Android Example (Demo App)

1. Initial Project Setup

Let’s move to Android Studio and create a new project with EmptyActivity template. Here I’m using package name is com.wave.foregroundservice. You can use as per your project need

2. Create a subclass of Service – ForgroundService.java

Just create a subclass of Service class in main package and override necessary methods.

package com.wave.foregroundservice;

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 android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;

public class ForegroundService extends Service {
    public static final String CHANNEL_ID = "ForegroundServiceChannel";

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String input = intent.getStringExtra("inputExtra");
        createNotificationChannel();
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                0, notificationIntent, 0);

        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("Foreground Service")
                .setContentText(input)
                .setSmallIcon(R.drawable.ic_stat_name)
                .setContentIntent(pendingIntent)
                .build();

        startForeground(1, notification);

        //do heavy work on a background thread


        //stopSelf();

        return START_NOT_STICKY;
    }

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

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

}

3. Create Notification Channel

For creating Notification Channel add below code in Foreground Service class

private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = new NotificationChannel(
                    CHANNEL_ID,
                    "Foreground Service Channel",
                    NotificationManager.IMPORTANCE_DEFAULT
            );

            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(serviceChannel);
        }
    }

Full Source code of ForegroundService.java

package com.wave.foregroundservice;

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 android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;

public class ForegroundService extends Service {
    public static final String CHANNEL_ID = "ForegroundServiceChannel";

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String input = intent.getStringExtra("inputExtra");
        createNotificationChannel();
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                0, notificationIntent, 0);

        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("Foreground Service")
                .setContentText(input)
                .setSmallIcon(R.drawable.ic_stat_name)
                .setContentIntent(pendingIntent)
                .build();

        startForeground(1, notification);

        //do heavy work on a background thread


        //stopSelf();

        return START_NOT_STICKY;
    }

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

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

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = new NotificationChannel(
                    CHANNEL_ID,
                    "Foreground Service Channel",
                    NotificationManager.IMPORTANCE_DEFAULT
            );

            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(serviceChannel);
        }
    }
}

4. Declare your service and add uses permission in Manifest.xml

Let’s open the AndroidManifest file, In this file, you have to add two things. first is to register the service inside the manifest. The second one is you need add uses permission FOREGROUND_SERVICE for android pie.

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

    <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/AppTheme">
        <service
            android:name=".ForegroundService"
            android:enabled="true"
            android:exported="true"></service>

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

5. Modify actviity_main.xml

Go to res=> layout and open activity_main.xml, I’m adding 2 button this layout one for start service another one for stop service.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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=".MainActivity">

    <Button
        android:id="@+id/buttonStartService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:background="@color/colorAccent"
        android:padding="16dp"
        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="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        android:background="@color/colorAccent"
        android:padding="16dp"
        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"
        app:layout_constraintVertical_bias="0.218" />
</android.support.constraint.ConstraintLayout>

6. Open MainActivity and add onClickListener on button

Let’s open MainActivity from src folder and add below code

package com.wave.foregroundservice;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    Button btnStartService, btnStopService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnStartService = findViewById(R.id.buttonStartService);
        btnStopService = findViewById(R.id.buttonStopService);

        btnStartService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startService();
            }
        });

        btnStopService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopService();
            }
        });
    }

    public void startService() {
        Intent serviceIntent = new Intent(this, ForegroundService.class);
        serviceIntent.putExtra("inputExtra", "Foreground Service Example in Android");

        ContextCompat.startForegroundService(this, serviceIntent);
    }

    public void stopService() {
        Intent serviceIntent = new Intent(this, ForegroundService.class);
        stopService(serviceIntent);
    }
}

Conclusion

Now your job is done, Your foreground service code is ready to run. Let’s run the project, Your app is up and running. While you click on ‘start service’ button than service will be started, and notification will appear on notification bar. Notification will disappear once you clicked on ‘stop service’ button.

I hope it’s helpful for you, then help me by sharing this post with all your friends who learning android app development.

If you have any queries, feel free to ask them in the comment section below. Happy Coding 🙂

Android Foreground Service Example in Kotlin

Android Jetpack is a set of component tools and guidance provided by Google for Android developers to make create android apps in the very efficient and effective manner. We have divided Jetpack component into four major categories as Foundation, Architecture, Behaviour and UI.

In this blog, I’m going to explain android architecture components. Android architecture components collection of party libraries that help you to design and build robust, testable and maintainable apps. Most importantly, You use architecture component you will have favour amount of boilerplate code hence your code should be cleaner and readable.

Architecture Components

  1. Data Binding
  2. LifeCycle Awareness
  3. ViewModel
  4. LiveData
  5. Room
  6. Navigation
  7. Work Manager
  8. Paging Library
Data Binding

Data Binding library allows us to bind to UI component in our layout data sources using a decorative format. This allows UI values to update automatically without manual intervention, which reduces a lot of boilerplate code in your app. Read More

LifeCycle Awareness

Every activity or Fragment in an Android application has a life cycle.  Life cycle status of activity to fragment always changes. When we can create separate classes with life cycle aware component we can create separate classes to observe the changes in life cycle state and act accordingly. This helps to create better organised and lightweight code, it is easier to maintain. Read More

ViewModel

The ViewModel is the modal class for a View which keeps data for View.  if it is required you can create separate ViewModel for each Activity and Fragment in your application. this class is designed to store and manage UI related data in a life cycle constancy. the ViewModel class allows data to service configuration changes. Such as screen rotation, keyboard changes language changes and enables multi-window mode. Read More

Live Data

Live Data- is an observable data holder class.  We can user live data to get real-time update user the using interfaces. Live Data only updates app component observers data in an active life cycle state. Live data does not replace RxJava but it allows us to perform some task done by RxJava in much easier manner. Read More

Room Persistence Library

It is a database persistence library is a great alternative to SqliteOpenHelper which have been used by Android developer for many years to work with SQLite database. Room access the wrapper around SQLite Database. Room reduces boilerplate code and makes sure code base cleaner and much readable. Read More

Navigation

It Helps developers to design the interactions that allow user to move across, into and back out from different content area within the app.  This includes the navigation UI class, which contains static methods which manage navigation with AppCompact bar and Navigation Drawer and Bottom Navigation.

Work Manager

There are lots of background processing task in an android application, likes and looks, upload data and sync database with remote server. You can create a background task and hand it off to WorkManager to run immediately or at an appropriate time. WorkManager is the latest and best way to perform background task based on different factor. such as  the device API level and App state

Paging Library

Paging Library makes it easier to load data to RecyclerView, step by step in your app using live data.  It supports to bounded and unbounded list both.

What is Service

When none of applications is active state than few Android components are being active in the background and that active component is actually the service. In other words, Service is an application component that executes task in the background without affecting user’s current activity. By default, Service always runs in the main UI thread, It does not runs in separate worker thread and also it is not run in a separate process.

Let’s take some example for better understand. Suppose a user is playing his game, This game is basically activity that shows the current interaction of the user and sometimes while playing the game in the background there are some operations that are going on.

For example while user is busy playing the game, there are few applications are getting updated from Play Store and we all have faced this situation where while interacting with any application in the background all of a sudden the application starts to get updated from the Google Play Store. While the other applications are being updated in the background that time operation is not affecting the current user interaction of playing the game. So all of these background operations is actually carried out by the Android component known as a service

For better clarity let me show you one more example. Suppose you are using the Facebook application and while using the Facebook application there are few background operations that are going on such as uploading or downloading of a file from some other application or while using the Facebook application you want to listen to the music. So here again these two operations are actually being carried out with the help of the Android component known as Service.
Now whenever background operations going on then all the background operations consume some memory. So other words you can say, whenever we use any application or perform any task it definitely eats up your device RAM.

Type of Service

types of service in android

In my opinion the service is broadly categorised into two types the first one is the Started Service and the second one is the Bound Service. The started service can be further categorised into two subcategory the first one can be called as the Foreground Service and the second one is the Background Service .

Now if you have a look at the DEVELOPER.ANDROID that is the official documentation of service then you will find that there are three types of service such as the Foreground, Background, and Bound Service but right now I thought it is much better to categorize the service in 2 subcategories of Started Service and the Bound Service

1. Started Service

Started Services is started with the help of an Android component(Activity, BroadcastReceiver, ContentProvider and Service). That why it is known as a Started Service. The Started service can be started by the Activity, BroadcastReceiver, ContentProvider and the Service itself. Here is noticeable point is that a service can start another service as well as.

The Started Service is starts with the help of a method of startService() method. Whenever any Android component start a Service the Service runs indefinitely in the background and even if the calling component is destroyed then also the started service will continue to run indefinitely in the background. Basically, I am trying to say is suppose the calling Android component is destroyed then also the started service continues to run and this might leads to memory leakage. The started service performs a single operation at a time and there is always a one way communication.

In case of started service that is we can pass the data from the Android component to the service but by default there is no mechanism to get back result from the service back to the calling component so we have to find a workaround to get back result and as said a service continues to run indefinitely in the background that why we should always call stopSelf() method or stopService() method to stop the service and avoid any memory leakage.

Let’s summarise Started Service in short
  • It started by Android components, these components are Activity, ContentProvider, BroadcastReceiver and Service itself.
  • It stared with help of startService() methods and stop by stopService() or stopSelf() methods.
  • When service once started its run in the background indefinitely even when the stared component is also destroyed.
  • By default it has one-way communication only.
  • We should stop the service after the task is finished by using stopService() or stopSelf() methods

2. Bound Service

The service is called a bound service when Android component simply bind to the particular service. We can bind service with three component. The components are Activity, ContentProvider and the Service itself. BroadcastReceiver can never bind the service. and binding to the service is achieved with the help of a special method of bindService() methods. A bind service exist as long as there is at least one component bound to it.

When this component is destroyed then the bound service is also destroyed simultaneously. So we can say that when all the calling components are destroyed then the service is also destroyed. In other words you can say, The Bound Service is dependent on the bounded component for its (own) existence. The bound service has a two way communication Unlike the started service where we had only one way communication so here in case of bound service we have the two way communication you can pass data from the component to the service and also by default get back result.

Summery of Bound Service
  • We can bind to the service with Activity, Content Provider and Service components with help of the bindService() method.
  • When all calling components are destroyed, the service also destroyed.
  • Bound Service continuously interacts with calling components.
  • By default is have two way communication.
1.1 What is Foreground Service

Suppose you are currently using the Gmail application and listening to the music that is being played by some other application. So music player is basically using the foreground service to play the music. The foreground service always uses the notification to notify the user that some long running operation is going on 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 application you see a notification that is performing some long running tasks that that service is basically the foreground service and the foreground service is always noticeable to the user that is the user is aware of this ongoing process.

Foreground Service is actually created by using the startForeground() method. So when we use this method it actually start the service to run in the foreground. And by using the stopForeground() method the service again returns back to run in the background and now its becoming the background service now.

I point is noticeable here that using stopForeground() method foreground service is not destroyed. Basically, it actually makes a foreground service to background service. So how to destroy the foreground service so for, that again you need to call the stopService() or stopSelf() the method to destroy the foreground service as well.

When a service runs in the foreground it should always be noticeable by the user to always use notification for the ongoing operation like we saw in case of music player application or downloading or uploading of the file or while updating the applications from the PlayStore we also have the notification to notify the user that some operation is going on.

1.2 What is background service

I will take example of the WhatsApp application and also the Gmail application by taking these two examples you can actually to correlated the things with the Facebook application as well.

Let take a example

Suppose you are connected to internet, Now you will simply turn off your Wi-Fi right. In case you have no internet on your phone. Means you are offline. Now let try to send some message to your friends WhatsApp account. So here you will just try to send a message like (Test message). After sending the message you are not connected to the internet that why this message is currently undelivered and it is showing a pending status close the application and let also destroy the WhatsApp application from the minimized application list. So right now I don’t have any running application and no recent items in the recent app.

Now just turn on Wi-Fi. Now device is connected with internet and message is automatically delivered without WhatsApp app open. In other words WhatsApp application is still closed you have not opened my WhatsApp application but still, my message was delivered to your friend’s device. how is that possible? This is simply because of background service. The WhatsApp application was actually running the background service and due to that service, my message was delivered in the background itself so we don’t need to open the WhatsApp application for our message to get delivered so this is the beauty of using the background service.

Conclusion

A service is started it is actually background in nature so when we use in the startService() method it actually creates a background service by default. Now starting from Android Oreo that is API 26 onwards there are certain restrictions imposed on the background service.

I will discuss it in my upcoming articles so please don’t worry about it and next to the background service is not noticeable by the user as we saw in case of WhatsApp and Gmail how they use the background service to send data to some other user in the background.