AdSense

AdSense3

Tuesday 18 August 2015

Android Service Tutorial

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.   
  11.     <Button  
  12.         android:id="@+id/buttonStart"  
  13.         android:layout_width="wrap_content"  
  14.         android:layout_height="wrap_content"  
  15.         android:layout_alignParentTop="true"  
  16.         android:layout_centerHorizontal="true"  
  17.         android:layout_marginTop="19dp"  
  18.         android:text="Start Service" />  
  19.   
  20.     <Button  
  21.         android:id="@+id/buttonStop"  
  22.         android:layout_width="wrap_content"  
  23.         android:layout_height="wrap_content"  
  24.         android:layout_above="@+id/buttonNext"  
  25.         android:layout_alignRight="@+id/buttonStart"  
  26.         android:layout_marginBottom="35dp"  
  27.         android:text="Stop Service" />  
  28.   
  29.     <Button  
  30.         android:id="@+id/buttonNext"  
  31.         android:layout_width="wrap_content"  
  32.         android:layout_height="wrap_content"  
  33.         android:layout_alignLeft="@+id/buttonStop"  
  34.         android:layout_centerVertical="true"  
  35.         android:text="Next Page" />  
  36.   
  37. </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.   
  11.     <TextView  
  12.         android:id="@+id/textView1"  
  13.         android:layout_width="wrap_content"  
  14.         android:layout_height="wrap_content"  
  15.         android:layout_alignParentLeft="true"  
  16.         android:layout_alignParentTop="true"  
  17.         android:layout_marginLeft="96dp"  
  18.         android:layout_marginTop="112dp"  
  19.         android:text="Next Page" />  
  20.   
  21. </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.   
  3. import android.app.Service;  
  4. import android.content.Intent;  
  5. import android.media.MediaPlayer;  
  6. import android.os.IBinder;  
  7. import android.widget.Toast;  
  8. public class MyService extends Service {  
  9.  MediaPlayer myPlayer;  
  10.  @Override  
  11.  public IBinder onBind(Intent intent) {  
  12.   return null;  
  13.  }  
  14.  @Override  
  15.  public void onCreate() {  
  16.   Toast.makeText(this"Service Created", Toast.LENGTH_LONG).show();  
  17.    
  18.   myPlayer = MediaPlayer.create(this, R.raw.sun);  
  19.   myPlayer.setLooping(false); // Set looping  
  20.  }  
  21.  @Override  
  22.  public void onStart(Intent intent, int startid) {  
  23.   Toast.makeText(this"Service Started", Toast.LENGTH_LONG).show();  
  24.   myPlayer.start();  
  25.  }  
  26.  @Override  
  27.  public void onDestroy() {  
  28.   Toast.makeText(this"Service Stopped", Toast.LENGTH_LONG).show();  
  29.   myPlayer.stop();  
  30.  }  
  31. }  

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.   
  15.       buttonStart = (Button) findViewById(R.id.buttonStart);  
  16.       buttonStop = (Button) findViewById(R.id.buttonStop);  
  17.       buttonNext = (Button) findViewById(R.id.buttonNext);  
  18.   
  19.       buttonStart.setOnClickListener(this);  
  20.       buttonStop.setOnClickListener(this);  
  21.       buttonNext.setOnClickListener(this);  
  22.      }  
  23.      public void onClick(View src) {  
  24.       switch (src.getId()) {  
  25.       case R.id.buttonStart:  
  26.        startService(new Intent(this, MyService.class));  
  27.        break;  
  28.       case R.id.buttonStop:  
  29.        stopService(new Intent(this, MyService.class));  
  30.        break;  
  31.       case R.id.buttonNext:  
  32.        Intent intent=new Intent(this,NextPage.class);  
  33.        startActivity(intent);  
  34.        break;  
  35.       }  
  36.      }  
  37. }  

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.   
  5. public class NextPage extends Activity {  
  6.  @Override  
  7.  public void onCreate(Bundle savedInstanceState) {  
  8.   super.onCreate(savedInstanceState);  
  9.   setContentView(R.layout.activity_next);  
  10.  }  
  11. }  

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.   
  7.     <uses-sdk  
  8.         android:minSdkVersion="8"  
  9.         android:targetSdkVersion="17" />  
  10.   
  11.     <application  
  12.         android:allowBackup="true"  
  13.         android:icon="@drawable/ic_launcher"  
  14.         android:label="@string/app_name"  
  15.         android:theme="@style/AppTheme" >  
  16.         <activity  
  17.             android:name="com.example.serviceexampleaudio.MainActivity"  
  18.             android:label="@string/app_name" >  
  19.             <intent-filter>  
  20.                 <action android:name="android.intent.action.MAIN" />  
  21.   
  22.                 <category android:name="android.intent.category.LAUNCHER" />  
  23.             </intent-filter>  
  24.         </activity>  
  25.           
  26.         <service  
  27.             android:name=".MyService"  
  28.             android:enabled="true" />  
  29.          <activity  
  30.             android:name=".NextPage"/>  
  31.     </application>  
  32.   
  33. </manifest>  

Output:

android service example output 1 android service example output 2

1 comment:

  1. this is very important topic
    your blog explains it invery easy way. this is best sitr for begginers to learn and
    develope their own small app

    ReplyDelete