Android Services

0
551

A service is one of the application components which helps a long-running operation to perform appropriately by keeping itself running in the background. A service does not require to communicate with the end user and it also keeps running even after the application gets destroyed.

Also Read: Android Activities

A service always takes place in two states which are started and bound.

S. No. State Descriptions
1 Started * A service enters into its first phase, started, whenever a component is called by the startService() method.
* After a service is called successfully, it can run for an indefinite period of time even if the component which started the service gets destroyed.
2 Bound * A service enters the bound phase whenever the component bound with it by the help of bindService() method.
* A bound service is capable of interacting with the end users by the help of the client-server interface.
* Other than interacting with the bound service, it can also send requests, receive responses, and perform Inter-Process Communication (IPC).

As already mentioned in earlier chapters, a service can monitor the service state changes with the help of the lifecycle callback methods. Based on these monitored changes, you can work accordingly at every stage. The following flowchart will help you to understand how both the states of a service actually work. It will also clarify the processing of startService() and bindService() methods.

service_lifecycle

Well, when you want to create a service, a Java class creation is required. This Java class needs to extend either the Service base class or any of the declared existing sub-classes. This Service base class contains numerous callback methods and a few of them are tabulated in the below provided table. As these callback methods are already defined in the base class so, you don’t need to implement them again. But it’s really important that you understand each and every callback method before you proceed further in the chapter.

S. No. Callback Methods Description
1 onStartCommand() * This callback method is called whenever any another component such as an activity requests to start the service.
* To start a service, startService() method is called.
* Always remember that once this method is implemented then it is important that the service is stopped once the work is done.
* To stop the service call either of the methods; stopSelf() method or stopService() method.
2 onBind() * This method is called whenever any other application component is being in need to bind to the service.
* bindService() method is called to bind with the service.
* For the implementation of the method, you need an interface for the interaction between the end users and the service.
* This interaction can only be achieved by returning the IBinder object to the method.
* It’s important that you always implement this method. But in any case, if you don’t want the binding to happen then the method must return the null value.
3 onUnbind() * This method is called by the system whenever all the clients get disconnected from a specific published interface.
* This published interface is a result of the service.
4 onRebind() * This method is called whenever new clients connect with the existing service.
* This can only be done after the notification of clients being disconnected by onUnbind(Intent).
5 onCreate() * This method is called after the creation of a service.
* A service can be created with the help of onStartCommand() method or onBind() method.
* This setup is required only once.
6 onDestroy() * This method is called by the system after a service gets destroyed.
* This method is responsible for the cleanup process. With the help of this method, resources such as threads, receivers, registered listeners, and others are cleaned up from the system.

The following program code will help you understand the life cycle callback methods more closely.

package com.w3school;

import android.app.Service;
import android.os.IBinder;
import android.content.Intent;
import android.os.Bundle;

public class HelloService extends Service
{
/** indicates how to behave if the service is killed */
int mStartMode;

/** interface for clients that bind */
IBinder mBinder;

/** indicates whether onRebind should be used */
boolean mAllowRebind;

/** Called when the service is being created. */
@Override
public void onCreate()
{ }

/** The service is starting, due to a call to startService() */
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
return mStartMode;
}

/** A client is binding to the service with bindService() */
@Override
public IBinder onBind(Intent intent)
{
return mBinder;
}

/** Called when all clients have unbound with unbindService() */
@Override
public boolean onUnbind(Intent intent)
{
return mAllowRebind;
}

/** Called when a client is binding to the service with bindService()*/
@Override
public void onRebind(Intent intent)
{ }

/** Called when The service is no longer used and is being destroyed */
@Override
public void onDestroy()
{ }
}

Now, take a look at the following example for a better understanding. The example will help you with a step-to-step guide in understanding the creation of your own Android Service. But this guide requires your understanding of the Hello World program.

Step 1: Start with opening Android Studio. Here, create an Android application and save it as My Application. Put this newly created application under the com.example.w3school.myapplication package.

Step 2: Now, make a few changes in the MainActivity.java file. This modification will include the declaration of startService() and stopService() methods.

Step 3: Create another java file with the name MyService.java. Keep this newly created file under the com.example.MyApplication package. This file will contain the methods which are required for the Android Service implementation.

Step 4: After this, service should be defined in AndroidManifest.xml file. For this, you need to make use of the <service…/> tag. You must also know that an application can have more than one services defined without any specific constraints.

Step 5: At this step, you need to modify another file which is res/layout/activity_main.xml. In this file, you need to add two buttons in a linear layout.

Step 6: Make sure you leave the contents of res/values/strings.xml file as it is because Android Studio IDE is capable of handling string values on its own.

Step 7: At last, just run the Android application on the Emulator to verify the result.

Below is the modified content of the MainActivity.java file. Here, you will find the fundamental life cycle callback methods which are startService() and stopService() methods. Well, startService() method is used to start a service while stopService() method is used to stop that service.

package com.example.w3school.myapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;

public class MainActivity extends Activity
{
String msg = “Android : “;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(msg, “The onCreate() event”);
}

public void startService(View view)
{
startService(new Intent(getBaseContext(), MyService.class));
}

// Method to stop the service
public void stopService(View view)
{
stopService(new Intent(getBaseContext(), MyService.class));
}
}

Now, take a look at the MyService.java file. As mentioned earlier, this file contains the implementation of various methods which are related to the Service. These methods are implemented on the basis of the requirements. But in here, we will be implementing onStartCommand() and onDestroy() methods.

package com.example.w3school.myapplication;

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

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

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
// Let it continue running until it is stopped.

Toast.makeText(this, “Service Started”, Toast.LENGTH_LONG).show();
return START_STICKY;
}

@Override
public void onDestroy()
{
super.onDestroy();
Toast.makeText(this, “Service Destroyed”, Toast.LENGTH_LONG).show();
}
}

Below is the modified content of the AndroidManifest.xml file. The <service…/> tag is included in it.

<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”

package=”com.example.w3chool.myapplication”>

<application
android:allowBackup=”true”
android:icon=”@mipmap/ic_launcher”
android:label=”@string/app_name”
android:supportsRtl=”true”
android:theme=”@style/AppTheme”>
<activity android:name=”.MainActivity”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
<service android:name=”.MyService” />
</application>
</manifest>

And the last file where the buttons are to be included is res/layout/activity_main.xml file.

<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools” android:layout_width=”match_parent”
android:layout_height=”match_parent” android:paddingLeft=”@dimen/activity_horizontal_margin”
android:paddingRight=”@dimen/activity_horizontal_margin”
android:paddingTop=”@dimen/activity_vertical_margin”
android:paddingBottom=”@dimen/activity_vertical_margin” tools:context=”.MainActivity”>

<TextView
android:id=”@+id/textView1″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Example of services”
android:layout_alignParentTop=”true”
android:layout_centerHorizontal=”true”
android:textSize=”30dp” />

<TextView
android:id=”@+id/textView2″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”W3School”
android:textColor=”#ff87ff09″
android:textSize=”30dp”
android:layout_above=”@+id/imageButton”
android:layout_centerHorizontal=”true”
android:layout_marginBottom=”40dp” />

<ImageButton
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/imageButton”
android:src=”@drawable/abc”
android:layout_centerVertical=”true”
android:layout_centerHorizontal=”true” />

<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/button2″
android:text=”Start Services”
android:onClick=”startService”
android:layout_below=”@+id/imageButton”
android:layout_centerHorizontal=”true” />

<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Stop Services”
android:id=”@+id/button”
android:onClick=”stopService”
android:layout_below=”@+id/button2″
android:layout_alignLeft=”@+id/button2″
android:layout_alignStart=”@+id/button2″
android:layout_alignRight=”@+id/button2″
android:layout_alignEnd=”@+id/button2″ />

</RelativeLayout>

Now, you just need to run the modified application of Hello World. We are assuming that you have already created the AVD during the environment setup. Well, to run this Android application, open any of the project files on the Android Studio IDE. Now, click on the Run icon to run the application. The tool will begin by installing the application on the created AVD and then runs it. The output will appear on the Emulator window only when the setup of your application completes successfully.

The display will have two buttons in the linear layout. These buttons will be Start Services and Stop Services. So, if the user wants to start a service then, he needs to click on the Start Services button and this will lead to the initiation of onStartCommand() method. And to confirm the proper functioning of the method, a message ‘Service Started’ will be displayed on the window. And if the user, hits on the Stop Services button then the stop will be stopped.