How to create simple (unbound) Service in Android?

 

Services in Android System

1) Faceless components: A service is a component which runs in the background without direct interaction with the user. As the service has no user interface, it is not bound to the lifecycle of an activity.

2) Taking care of long running background tasks: Services are used for repetitive and potentially long running operations, i.e., Internet downloads, checking for new data, data processing, updating content providers and the like.

3) Runs on UI Thread: By default a service runs in the same process as the main thread of the application.

Therefore you need to use asynchronous processing in the service to perform resource intensive tasks in the background. A common used pattern for a service implementation is to create and run a new Thread in the service to perform the processing in the background and then to terminate the service once it has finished the processing.

Services which run in the process of the application are sometimes called local services.

4)Unaffected by activity switching: Each Service has a specific job, and they keep at it if you switch between different Activities, or even if you switch to a different application altogether.

In Android a Service is used for two main reason:

  • Implement multi-task

  • Enable Inter-Process-Communication (IPC)

A typical example of the first case is an app that required to download data from a remote server, in this case we can have Activity that interacts with a user and starts a service that accomplishes the work in background while the user can use the app and maybe when the service finishes sends a message to the user.

In the second case, we want to “share” some common functions so that different app can re-use them. For example, we can suppose we have a service that sends an email and we want to share this service among several apps so that we don’t have to rewrite the same code. In this case we can use IPC so that the service exposes a “remote” interface that can be called by other app.

service_lifecycle

Forms of Service

A Service can have two forms:

1) Started/Unbound: In this case, an application component starts the service by calling startService() , and it would continue to run in the background, even if the original component that initiated it is destroyed. For instance, when started, a service would continue to play music in the background indefinitely.

2) Bound: An Android component may bind itself to a Service using bindservice (). A bound service would run as long as the other application components are bound to it. As soon as they unbind, the service destroys itself.

An unbound activity runs indefinitely, whereas the lifespan of a bound activity depends on the application components that bind to it.

The following diagram on the left shows the lifecycle when the service is created with startService() and the diagram on the right shows the lifecycle when the service is created with bindService(): (image courtesy : android.com )

CallBacks of Service:

Callback Description
onStartCommand() The system calls this method when another component, such as an activity, requests that the service be started, by calling startService(). If you implement this method, it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService() methods.
onBind() The system calls this method when another component wants to bind with the service by calling bindService(). If you implement this method, you must provide an interface that clients use to communicate with the service, by returning an IBinder object. You must always implement this method, but if you don’t want to allow binding, then you should return null.
onUnbind() The system calls this method when all clients have disconnected from a particular interface published by the service.
onRebind() The system calls this method when new clients have connected to the service, after it had previously been notified that all had disconnected in its onUnbind(Intent).
onCreate() The system calls this method when the service is first created using onStartCommand() or onBind(). This call is required to perform one-time setup.
onDestroy() The system calls this method when the service is no longer used and is being destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, receivers, etc.

onStartCommand() method has integer return type value which can be any of the following:

START_STICKY : Using this return value, if the OS kills our Service it will recreate it but the Intent that was sent to the Service isn’t redelivered. In this way the Service is always running

START_NOT_STICKY: If the OS kills the Service it won’t recreate it until the client calls explicitly onStart command

START_REDELIVER_INTENT: It is similar to the START_STICKY and in this case the Intent will be redelivered to the service.

Steps to Create a Simple Service:

This code starts and stops a simple service, plays a music in background.

1) Firstly create “raw” folder inside res folder and place music file in it. Here it is song.mp3

service1

2) Add the service in manifest file:

<service 
 android:name=".MyService"/>

3) Layout will contain two buttons play and stop. Play will start the service of playing music and Stop will stop the music.

(layout_main.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" >
 <Button 
 android:id="@+id/button1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="@string/play"/>
 <Button 
 android:id="@+id/button2"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="@string/stop"/>
 

</LinearLayout>

The MainActivity.java file calls the service on pressing the button:

package com.example.simpleservice;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.layout_main);
 Button play,stop;
 play = (Button)findViewById(R.id.button1);
 play.setOnClickListener(new OnClickListener(){
 @Override
 public void onClick(View view){
 Intent myIntent = new Intent(MainActivity.this, MyService.class);
 startService(myIntent);
 }
 });
 
 stop=(Button)findViewById(R.id.button2);
 stop.setOnClickListener(new OnClickListener(){
 @Override
 public void onClick(View view){
 Intent myIntent = new Intent(MainActivity.this, MyService.class);
 stopService(myIntent);
 }
 });

 }
}

The main Service code resides in MyService.java file:

package com.example.simpleservice;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

public class MyService extends Service{
 String tag="MyService";
 MediaPlayer mp;
 
 @Override
 public IBinder onBind(Intent intent){
 return null;
 }
 @Override
 public void onCreate(){
 super.onCreate();
 mp = MediaPlayer.create(getApplicationContext(), R.raw.song);
 }
 
 @Override
 public int onStartCommand(Intent intent, int flags, int startId){
 mp.start();
 return START_STICKY;
 }
 
 @Override
 public void onDestroy(){
 mp.release();
 super.onDestroy();
 }

}

Its done. Click on play button to play the music and stop button to stop the music.

 

Advertisements

About Priyanka Kapoor

Simple, Hardworking & friendly.....
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s