Service in Android – Android Tutorial

Service in Android – Tutorial in Android Studio

As important as an Activity is for android, Service is really important to provide the ability to handle lot of activities like, performing background tasks (Like playing songs, interacting with a  server) and foreground tasks as well.

It does not have any UI and acts without any hooks to control it. We will see about its flow and how to create one below.

The term Bind is often used, as you can create 3 types of Services. They are,

Foreground

A foreground service performs some operation that is noticeable to the user. For example, an audio app would use a foreground to play an audio track. We will definitely have to attach a notification if the Foreground service is created. This will let the user know that the application is still doing some task even after switching the phone off, or exiting the application. (There are lot of restrictions to a background service like we will see below.)

Background

A background service performs an operation that isn’t directly noticed by the user. For example, if an app uses a service to compact its storage, that would usually be a backgroundService. It is to be noted that, a BackgroundService cannot run, if the user at some point exits the application. There are also restrictions on it being killed by the OS if there is a higher priority thread that has to be run.

Bound

A service is bound when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, receive results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. This is useful, if you are performing an activity with respect to an activity. Bound services have their own set of advantages and disadvantages.

Creating a Simple Service

We will look at creating a background service in this section. We will need to leverage two methods startService() and stopService(). This starts and stops services as an when needed by the activity.

The background services start running endlessly until the OS kills it or the stopService() method is called. There is another way the service can kill itself, by using the stopSelf() method.

Basics of Service Class

We will have to know about usage of the class Service. This class is the base class for creating any Service.We will be overriding some important methods like below.

onStartCommand()

The system invokes this method by calling startService() when another component (such as an activity) requests that the service be started.

onBind()

The system invokes this method by calling bindService() when another component wants to bind with the service (such as to perform RPC). In your implementation of this method, you must provide an interface that clients use to communicate with the service by returning an IBinder. We will see about it in the below sections.

onCreate()

The system invokes this method to perform one-time setup procedures when the service is initially created (before it calls either onStartCommand() or onBind()). If the service is already running, this method is not called.

onDestroy()

The system invokes this method when the service is no longer used and is being destroyed. This will clean up all the resources created during onCreate()

Example Class to create a simple Background Service

We will be needing 2 Classes and one Layout file like below. We will be using a TextView and a Button

main_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView
        android:id="@+id/text_service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Service Example"
        android:layout_marginTop="10dp" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:id="@+id/start"
        android:text="Start Service"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:id="@+id/stop_Service"
        android:text="Stop Service"/>

</LinearLayout>

ServiceActivity.java – This is the class that performs the Services call.

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;

public class ServiceActivity extends Activity{
    Button startService;
    Button stopService;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
        startService = (Button) findViewById(R.id.start);
        stopService = (Button) findViewById(R.id.stop_Service);

        startService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startService(new Intent(v.getContext(),SampleService.class));

            }
        });
        stopService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopService(new Intent(v.getContext(),SampleService.class));
            }
        });
    }

}

SampleService.java – This is our serviceclass to provide the backgroundService.

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;

public class SampleService extends Service{
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();

    }
    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();

    }
    @Override
    public void onDestroy() {
        Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
    }
}

Once the classes are added, do not forget to add the <Service> to your Manifest.xml like below.

<service
    android:name=".SampleService"
    android:enabled="true" />
The final Output

"<yoastmark

 

This is a basic implementation of a backgroundService. Drop in any comments below.

Conclusion

It is quite imperative how effective the need for a background and a ForegroundService can be. It is also to be noted that, there are some difficulties in understanding how a service is run and created. This is because of a very mucky abstraction layer built below the Android Systems. However, Services are very important to the operation of a Native application.

For more information regarding Foreground/Bounded services. Check here.

“Learn and Be Curious”

Leave a Comment