Friday, 10 June 2016

Services in Android

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.

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.


Activity_Main.XML


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="68dp"
        android:text="Start Service" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="136dp"
        android:text="Stop service" />

</RelativeLayout>

 ActivityMain.Java


package com.example.service;

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

public class MainActivity extends Activity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
         
Button startServiceButton = (Button)findViewById(R.id.button1);
       
        startServiceButton.setOnClickListener(new OnClickListener() {
  

@Override
public void onClick(View v) {
   // TODO Auto-generated method stub
   Intent in = new Intent(getApplicationContext(), MyService.class);
    startService(in);
  
}
  });
        Button stopServiceButton = (Button)findViewById(R.id.button2);
       
        stopServiceButton.setOnClickListener(new OnClickListener() {
  
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Intent in = new Intent(getApplicationContext(), MyService.class);
                stopService(in);
   }
  });
   }
}

MyService.Java

package com.example.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service{

       @Override
       public IBinder onBind(Intent intent) {
              // TODO Auto-generated method stub
              return null;
       }
       @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
         // TODO Auto-generated method stub
         Toast.makeText(getApplicationContext(), "service started", 3000).show();
         return super.onStartCommand(intent, flags, startId);
        }
        @Override
        public void onDestroy() {
         Toast.makeText(getApplicationContext(), "service stopped", 3000).show();
         super.onDestroy();
        }
}

 
AndroidManifest.XMl

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.service"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="MyService"></service>
    </application>

</manifest>

Output








No comments:

Post a Comment

Ads Inside Post