Using services in android application

Syed M Idris
Byteridge
Published in
4 min readFeb 2, 2012

Talking about Services Lifecycle, we are actually moving beyond the onDemand service. An onDemand Service is initiated when required, and terminated as soon as the work is done. But we can actually go much beyond that. We have many more interactions available in android. They don’t have to be limited to performing simple tasks.

A Service can do all kinds of things in the background even when no direct request has been made. To create an application to be run in the background of other current activities, one needs to create a Service. The Service can run indefinitely (unbounded) or can run at the lifespan of the calling activity (bounded).

Service is a fundamental component in android. Many a time, applications will need to run processes for a long time without any intervention from the user, or very rare interventions. These background processes need to keep running even when the phone is being used for other activities / tasks. To accommodate for such a requirement, android has introduced the “Service” component.

Services can provide user-oriented features. There are three primary service class methods through which the services lifecycle is exposed.

  • onCreate
  • onStartCommand
  • onDestroy

Please note that a Service has a different lifecycle than activities, and hence has different methods. But to begin a service in the application, a call to startService() is made which invokes the service onCreate() method. Then onStart() method runs the service.

onCreate

  • Called when android creates the class
  • A service class instance can call this method only once

If you start a service, an onCreate method gets instantiated.
From the next time, an onStartCommand is called if the service is requested.

onStartCommand

  • Called every time another component calls Context.startService for this service
  • Instance that requires the service may call this method any number of times

This is Primary mechanism by which requests are passed to the service.
At first when service class is called, onCreate and onStartCommand methods are called. From the next time, only onStartCommand method will be called.

onDestroy

  • Called to notify the service that is being shut down.
  • Another component calls Context.StopService or the service calls stopSelf
  • Also called if a service needs to shutdown another service for resource reasons.

In this blog, a very simple service is introduced which runs in the background. Following are the steps to create a demo service in Android.

Step 1
This Services class is simple as it starts an audio (m4a) file and the start button invokes the “MySimpleService” service.
ServicesController.java

Button Startbutton, Stopbutton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Startbutton = (Button) findViewById(R.id.buttonStart);
Stopbutton = (Button) findViewById(R.id.buttonStop);
Startbutton.setOnClickListener(this);
Stopbutton.setOnClickListener(this);
}

public void onClick(View button) {
switch (button.getId()) {
case R.id.buttonStart:
Log.d(TAG, “onClick: starting service”);
startService(new Intent(this, MySimpleService.class));
break;
case R.id.buttonStop:
Log.d(TAG, “onClick: stopping service”);
stopService(new Intent(this, MySimpleService.class));
break;
}
}

Step2
Let us create a service class that extends android.app.Service.
This service just displays a message when started and again displays a message when stopped. Hence the onStart() and onDestroy() methods are implemented.

Here is the code.

public class MySimpleService extends Service {
private static final String TAG = “MySimpleService”;
MediaPlayer musicplayer;

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

@Override
public void onCreate() {
Toast.makeText(this, “Service Created”, Toast.LENGTH_LONG).show();
Log.d(TAG, “onCreate”);

musicplayer = MediaPlayer.create(this, R.media.bytemusic);
musicplayer.setLooping(false); // Set looping
}

@Override
public void onDestroy() {
Toast.makeText(this, “Service Destroyed”, Toast.LENGTH_LONG).show();
Log.d(TAG, “onDestroy”);
musicplayer.stop();
}

@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, “Service Started”, Toast.LENGTH_LONG).show();
Log.d(TAG, “onStart”);
musicplayer.start();
}
}

Step3
Necessary to make the entry for this service in AndroidManifest .xml file.

<service android:enabled=”true” android:name=”.MySimpleService” />

Code for main XML file

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=”fill_parent”
android:layout_height=”fill_parent”>
<TextView android:text=”Byteridge” <! — Add your Textview’s code here → >
</TextView>
<TextView android:text=”Services” <! — Add your Textview’s code here → >
</TextView>
<Button android:text=”Start the music” <! — Add your Textview’s code here → >
</Button>
<Button android:text=”Stop the music” <! — Add your Textview’s code here → >
</Button>
</LinearLayout>

--

--