Wednesday, 20 November 2013

IntentService Example in Android

IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.


Check output in LogCat.

step1: create a new project.
Step2: create new java class that extends with IntentService class.
step3: Call IntentService in Activity using startService() method.


ProjectName : IntentService
XML Layouts : activity_main.xml
Java Classes: MainActivity, MyService

strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">IntentService</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="button_title">Start Service</string>

</resources>

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"
    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" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="94dp"
        android:onClick="startService"
        android:text="@string/button_title" />

</RelativeLayout>

MyService.java:
package com.ram.intentservice;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

public class MyService extends IntentService {

public MyService() {
super("helloservice");
// TODO Auto-generated constructor stub
}

@Override
public void onCreate() {
super.onCreate();
Log.d("Intent Service", "service created");
}

@Override
protected void onHandleIntent(Intent intent) {
Log.d("Intent Service", "service started");
synchronized (intent) {

}
}

}

MainActivity.java:
package com.ram.intentservice;

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

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void startService(View v) {
Intent in = new Intent(getApplicationContext(), MyService.class);
startService(in);
}

}