Android Services With Examples
Android Services With Examples
In android, Service is a component which keep an app running in the background to perform long-running
operations based on our requirements. For Service, we don’t have any user interface and it will run the apps in the
background like playing the music in the background or handle network operations when the user in a different
app.
Started Service
A service is Started when an application component, such as an activity calls startService() method. Once it
started, it will run indefinitely in background even if the component that started is destroyed.
We can stop the Started service by using stopService() method or the service can stop itself by
calling stopSelf() method. In android, the Started service component will perform a single operation and it
won’t return any result to the caller.
Bound Service
A service is Bound when another application component calls bindService() method. The bound service runs
as long as another application component is bound to it.
We can unbind the service by calling unbindService() method based on our requirements. In android, we can
bind multiple components to a single service at once, but the service will be destroyed in case all the components
unbind.
Create a Service
Generally, in android to create a service we must create a subclass of Service or use one of existing subclass. In
android the application component such as an activity can start the service by calling startService() which
results in calling the service’s onStartCommand() method.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO write your own code
return Service.START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
}
Start a Service
In android, the component such as an activity, service or receiver can start the service
using startService() method. Following is the sample code snippet of starting a service using
the startService method.
onStartCommand()
The system will invoke this method when another component such as an activity requests the service to be started
by calling startService(). When this method executed, the service will start and run indefinitely in background. If
we implement this in our code, it’s our responsibility to stop the service once code execution is done by
calling stopSelf() or stopService() methods. In case, if we want to provide only binding, then we don’t
need to implement this method.
In android, onStartCommand() method must return an integer and the integer is a value that describes how the
system will continue the service in the event that the system kills it.
The onStartCommand() method will return a value from one of the following constants.
Option Description
START_STICKY It will restart the service in case if it terminated and the Intent data
which is passed to the onStartCommand() method is NULL. This is
Option Description
suitable for the service which are not executing commands but
running independently and waiting for the job.
START_NOT_STICKY It will not restart the service and it is useful for the services which
will run periodically. The service will restart only when there are a
pending startService() calls. It’s the best option to avoid running a
service in case if it is not necessary.
onBind()
The system will invoke this method when another component wants to bind with the service by
calling bindService() . During implementation of this method, we must need to provide an interface to the
clients to communicate with the service by returning an IBinder object. In android, we must need to implement
this method, in case if we don’t need to allow binding, then we should return NULL.
onCreate()
The system will invoke this method when the service is created initially
using onStartCommand() or onBind() methods to do one-time setup procedures. In case, if the service is
already running, then this method will not call.
onDestroy()
The system will invoke this method when the service is no longer used and is being destroyed. This is the final call
that the service will receive and we need to implement this method in our service to clean up any unused
resources such as threads, receivers or listeners.
Generally, in android if we start a service by calling startService() method, the service will run continuously
even if the component that started service is destroyed until we stop it by using stopService() or it stops itself
with stopSelf() .
Same way, if we create a service by calling bindService() method, the service will runs as long as the
component is bound to it. After the service is unbound from all of its clients, the system will destroy it.
In android, the service life cycle is having a set of callback methods that need to be implemented to keep a track
of services status and to execute the required things in appropriate-time.
package com.tutlane.services;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
@Override
public void onCreate() {
// The service is being created
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// The service is starting, due to a call to startService()
return mStartMode;
}
@Override
public IBinder onBind(Intent intent) {
// A client is binding to the service with bindService()
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
// All clients have unbound with unbindService()
return mAllowRebind;
}
@Override
public void onRebind(Intent intent) {
// A client is binding to the service with bindService(),
// after onUnbind() has already been called
}
@Override
public void onDestroy() {
// The service is no longer used and is being destroyed
}
}
Create a new android application using android studio and give names as Services. In case if you are not aware of
creating an app in android studio check this article Android Hello World App.
Now we need to create our own custom service file MyService.java in \java\com.tutlane.services path to define
our actual provider and associated methods for that right-click on your application folder à Go
to New à select Java Class and give name as MyService.java.
Once we create a new file MyService.java, open it and write the code like as shown below
MyService.java
package com.tutlane.services;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;
import android.widget.Toast;
/**
* Created by Tutlane on 02-08-2017.
*/
Now open activity_main.xml file from \src\main\res\layout path and write the following code.
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startService"
android:layout_marginLeft="130dp"
android:layout_marginTop="150dp"
android:text="Start Service"/>
<Button
android:id="@+id/btnstop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="stopService"
android:layout_marginLeft="130dp"
android:layout_marginTop="20dp"
android:text="Stop Service"/>
</LinearLayout>
Now open MainActivity.java file from \java\com.tutlane.services path and write following to implement custom
broadcast intents.
MainActivity.java
package com.tutlane.services;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// Start the service
public void startService(View view) {
startService(new Intent(this, MyService.class));
}
// Stop the service
public void stopService(View view) {
stopService(new Intent(this, MyService.class));
}
}
Now we need to register our service in android manifest file (AndroidManifest.xml) using <service> attribute
like as shown below.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutlane.services">
<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">
<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>