Android Service and IntentService

Service is an application component. Service which runs on background for a long time without a help of user interface.

Service can even start up from another application component like Activity,Broadcast receiver and it will continue to run in the background even if the user switches to another application.
For example, a service might handle network transactions, play music, perform file I/O from the background.

Android has two type of service namely
1.Service
2.IntentService

Difference between these two services are
Service run on main UI Thread, while IntentService creates a worker thread and uses that thread to run the service. IntentService creates a queue that passes one intent at a time to onHandleIntent().

Service want to stop manually by stopService() and stopSelf(). Meanwhile,IntentService will stop automatically after the completion of work.
IntentService implements onStartCommand() that sends Intent to queue and to onHandleIntent().

Create Android Project with name as "ServiceDemo" with package name "com.thulasiram.servicetest". MainActivity will start and stop Services. This is the code for MainActivity. 


package com.thulasiram.servicetest;

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

public class MainActivity extends Activity {
Button local_service,intent_service;
@Override
protected void onCreate(Bundle savedInstanceState) {  

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
local_service = (Button)findViewById(R.id.local_service);
intent_service = (Button)findViewById(R.id.intent_service);

local_service.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                    if(local_service.getText().equals("Start Local Service")){
            local_service.setText("Stop Local Service");
            startService(new Intent(MainActivity.this,LocalServiceDemo.class));
        }else if(local_service.getText().equals("Stop Local Service")){
    local_service.setText("Start Local Service");
    stopService(new Intent(MainActivity.this,LocalServiceDemo.class));
        }
                  }
             });

     intent_service.setOnClickListener(new View.OnClickListener() {
                 public void onClick(View v) {    
      startService(new Intent(MainActivity.this,IntentServiceDemo.class));
                 }
            });

}
}

Create "LocalServiceDemo"  class. It will Managing the Lifecycle of a Service.

package com.thulasiram.servicetest;

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

public class LocalServiceDemo extends Service{  

@Override
         public void onCreate() {
    Toast.makeText(getApplicationContext(), "Local Service Created",                                                   Toast.LENGTH_LONG).show();
         }

    @Override  
    public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(getApplicationContext(), "Local Service Started", Toast.LENGTH_LONG).show();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
    Toast.makeText(getApplicationContext(), "Local Service Destroyed",    Toast.LENGTH_LONG).show();
    }

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

}

Create "IntentServiceDemo"  class. It will Managing the Lifecycle of a IntentService.

package com.thulasiram.servicetest;

import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
import android.widget.Toast;

public class IntentServiceDemo extends IntentService{
Handler handler = null; 
public IntentServiceDemo() { 
super("IntentServiceDemo");
handler = new Handler();
}
@Override
    public void onCreate() {
super.onCreate();
Toast.makeText(getApplicationContext(), "Intent Service Created",   Toast.LENGTH_LONG).show();
    }

@Override
public int onStartCommand(Intent intent, int flags, int startId) {  
     super.onStartCommand(intent, flags, startId);
     Toast.makeText(getApplicationContext(), "Intent Service Started",     Toast.LENGTH_LONG).show();
     return START_STICKY;
}

@Override
protected void onHandleIntent(Intent intent) {
    handler.post(new Runnable() { 
                @Override
                public void run() {
                   Toast.makeText(getApplicationContext(), "Intent Service onHandled",    Toast.LENGTH_LONG).show();
                }
            });
}
@Override
    public void onDestroy() {
super.onDestroy();
    Toast.makeText(getApplicationContext(), "Intent Service Destroyed",         Toast.LENGTH_LONG).show();
    }

}

paste below code to "activity_main.xml" file

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/local_service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/intent_service"
        android:layout_alignParentTop="true"
        android:layout_marginTop="85dp"
        android:text="@string/start_local_service" />

    <Button
        android:id="@+id/intent_service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/local_service"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="89dp"
        android:text="@string/start_intent_service"/>

</RelativeLayout>

paste below code to "strings.xml" file

<string name="start_local_service">Start Local Service</string>
<string name="stop_local_service">Stop Local Service</string>
<string name="start_intent_service">Start Intent Service</string>

paste below code to "AndroidManifest.xml" inside of application element.

<service android:name="com.thulasiram.servicetest.LocalServiceDemo"></service>
<service android:name="com.thulasiram.servicetest.IntentServiceDemo"></service>

you can download source code here

Comments

  1. thank you that is very clean code helped me so much

    ReplyDelete

Post a Comment

Popular posts from this blog

SQLiteDatabase With Multiple Tables

Programmatically turn ON/OFF WiFi on Android device