Cheap VPS & Xen Server


Residential Proxy Network - Hourly & Monthly Packages

Android Service


Android service is a component that is used to perform operations on the background such as playing music, handle network transactions, interacting content providers etc. It doesn’t has any UI (user interface).

The service runs in the background indefinitely even if application is destroyed.

Moreover, service can be bounded by a component to perform interactivity and inter process communication (IPC).

The android.app.Service is subclass of ContextWrapper class.

Note: Android service is not a thread or separate process.

Life Cycle of Android Service

There can be two forms of a service.The lifecycle of service can follow two different paths: started or bound.

  1. Started
  2. Bound

1) Started Service

A service is started when component (like activity) calls startService() method, now it runs in the background indefinitely. It is stopped by stopService() method. The service can stop itself by calling the stopSelf() method.

2) Bound Service

A service is bound when another component (e.g. client) calls bindService() method. The client can unbind the service by calling the unbindService() method.

The service cannot be stopped until all clients unbind the service.

service_lifecycle

Understanding Started and Bound Service by background music example

Suppose, I want to play music in the background, so call startService() method. But I want to get information of the current song being played, I will bind the service that provides information about the current song.


Android Service Example

Let’s see the example of service in android that plays an audio in the background. Audio will not be stopped even if you switch to another activity. To stop the audio, you need to stop the service.

activity_main.xml

Drag the 3 buttons from the pallete, now the activity_main.xml will look like this:

File: activity_main.xml
  1. <RelativeLayout xmlns:androclass=“http://schemas.android.com/apk/res/android”
  2.     xmlns:tools=“http://schemas.android.com/tools”
  3.     android:layout_width=“match_parent”
  4.     android:layout_height=“match_parent”
  5.     android:paddingBottom=“@dimen/activity_vertical_margin”
  6.     android:paddingLeft=“@dimen/activity_horizontal_margin”
  7.     android:paddingRight=“@dimen/activity_horizontal_margin”
  8.     android:paddingTop=“@dimen/activity_vertical_margin”
  9.     tools:context=“.MainActivity” >
  10.     <Button
  11.         android:id=“@+id/buttonStart”
  12.         android:layout_width=“wrap_content”
  13.         android:layout_height=“wrap_content”
  14.         android:layout_alignParentTop=“true”
  15.         android:layout_centerHorizontal=“true”
  16.         android:layout_marginTop=“19dp”
  17.         android:text=“Start Service” />
  18.     <Button
  19.         android:id=“@+id/buttonStop”
  20.         android:layout_width=“wrap_content”
  21.         android:layout_height=“wrap_content”
  22.         android:layout_above=“@+id/buttonNext”
  23.         android:layout_alignRight=“@+id/buttonStart”
  24.         android:layout_marginBottom=“35dp”
  25.         android:text=“Stop Service” />
  26.     <Button
  27.         android:id=“@+id/buttonNext”
  28.         android:layout_width=“wrap_content”
  29.         android:layout_height=“wrap_content”
  30.         android:layout_alignLeft=“@+id/buttonStop”
  31.         android:layout_centerVertical=“true”
  32.         android:text=“Next Page” />
  33. </RelativeLayout>

activity_next.xml

It is the layout file of next activity.

File: activity_next.xml

It contains only one textview displaying the message Next Page

  1. <RelativeLayout xmlns:androclass=“http://schemas.android.com/apk/res/android”
  2.     xmlns:tools=“http://schemas.android.com/tools”
  3.     android:layout_width=“match_parent”
  4.     android:layout_height=“match_parent”
  5.     android:paddingBottom=“@dimen/activity_vertical_margin”
  6.     android:paddingLeft=“@dimen/activity_horizontal_margin”
  7.     android:paddingRight=“@dimen/activity_horizontal_margin”
  8.     android:paddingTop=“@dimen/activity_vertical_margin”
  9.     tools:context=“.MainActivity” >
  10.     <TextView
  11.         android:id=“@+id/textView1”
  12.         android:layout_width=“wrap_content”
  13.         android:layout_height=“wrap_content”
  14.         android:layout_alignParentLeft=“true”
  15.         android:layout_alignParentTop=“true”
  16.         android:layout_marginLeft=“96dp”
  17.         android:layout_marginTop=“112dp”
  18.         android:text=“Next Page” />
  19. </RelativeLayout>

Service class

Now create the service implemenation class by inheriting the Service class and overridding its callback methods.

File: MyService.java
  1. package com.example.serviceexampleaudio;
  2. import android.app.Service;
  3. import android.content.Intent;
  4. import android.media.MediaPlayer;
  5. import android.os.IBinder;
  6. import android.widget.Toast;
  7. public class MyService extends Service {
  8.  MediaPlayer myPlayer;
  9.  @Override
  10.  public IBinder onBind(Intent intent) {
  11.   return null;
  12.  }
  13.  @Override
  14.  public void onCreate() {
  15.   Toast.makeText(this“Service Created”, Toast.LENGTH_LONG).show();
  16.   myPlayer = MediaPlayer.create(this, R.raw.sun);
  17.   myPlayer.setLooping(false); // Set looping
  18.  }
  19.  @Override
  20.  public void onStart(Intent intent, int startid) {
  21.   Toast.makeText(this“Service Started”, Toast.LENGTH_LONG).show();
  22.   myPlayer.start();
  23.  }
  24.  @Override
  25.  public void onDestroy() {
  26.   Toast.makeText(this“Service Stopped”, Toast.LENGTH_LONG).show();
  27.   myPlayer.stop();
  28.  }
  29. }

Activity class

Now create the MainActivity class to perform event handling. Here, we are writing the code to start and stop service. Additionally, calling the second activity on buttonNext.

File: MainActivity.java
  1. package com.example.serviceexampleaudio;
  2. import android.app.Activity;
  3. import android.content.Intent;
  4. import android.os.Bundle;
  5. import android.view.View;
  6. import android.view.View.OnClickListener;
  7. import android.widget.Button;
  8. public class MainActivity extends Activity implements OnClickListener {
  9.      Button buttonStart, buttonStop,buttonNext;
  10.      @Override
  11.      public void onCreate(Bundle savedInstanceState) {
  12.       super.onCreate(savedInstanceState);
  13.       setContentView(R.layout.activity_main);
  14.       buttonStart = (Button) findViewById(R.id.buttonStart);
  15.       buttonStop = (Button) findViewById(R.id.buttonStop);
  16.       buttonNext = (Button) findViewById(R.id.buttonNext);
  17.       buttonStart.setOnClickListener(this);
  18.       buttonStop.setOnClickListener(this);
  19.       buttonNext.setOnClickListener(this);
  20.      }
  21.      public void onClick(View src) {
  22.       switch (src.getId()) {
  23.       case R.id.buttonStart:
  24.        startService(new Intent(this, MyService.class));
  25.        break;
  26.       case R.id.buttonStop:
  27.        stopService(new Intent(this, MyService.class));
  28.        break;
  29.       case R.id.buttonNext:
  30.        Intent intent=new Intent(this,NextPage.class);
  31.        startActivity(intent);
  32.        break;
  33.       }
  34.      }
  35. }

NextPage class

Now, create another activity.

File: NextPage.java
  1. package com.example.serviceexampleaudio;
  2. import android.app.Activity;
  3. import android.os.Bundle;
  4. public class NextPage extends Activity {
  5.  @Override
  6.  public void onCreate(Bundle savedInstanceState) {
  7.   super.onCreate(savedInstanceState);
  8.   setContentView(R.layout.activity_next);
  9.  }
  10. }

Declare the Service in the AndroidManifest.xml file

Finally, declare the service in the manifest file.

File: AndroidManifest.xml

Let’s see the complete AndroidManifest.xml file

  1. <?xml version=“1.0” encoding=“utf-8”?>
  2. <manifest xmlns:androclass=“http://schemas.android.com/apk/res/android”
  3.     package=“com.example.serviceexampleaudio”
  4.     android:versionCode=“1”
  5.     android:versionName=“1.0” >
  6.     <uses-sdk
  7.         android:minSdkVersion=“8”
  8.         android:targetSdkVersion=“17” />
  9.     <application
  10.         android:allowBackup=“true”
  11.         android:icon=“@drawable/ic_launcher”
  12.         android:label=“@string/app_name”
  13.         android:theme=“@style/AppTheme” >
  14.         <activity
  15.             android:name=“com.example.serviceexampleaudio.MainActivity”
  16.             android:label=“@string/app_name” >
  17.             <intent-filter>
  18.                 <action android:name=“android.intent.action.MAIN” />
  19.                 <category android:name=“android.intent.category.LAUNCHER” />
  20.             </intent-filter>
  21.         </activity>
  22.         <service
  23.             android:name=“.MyService”
  24.             android:enabled=“true” />
  25.          <activity
  26.             android:name=“.NextPage”/>
  27.     </application>
  28. </manifest>

Output:

service1

service2

Comments

comments