Android Basics – Learn how to create a Started Service using an IntentService

In the last Article you learnt about Android Services and the difference between a bound and a started service. In this Article you will learn how to call the IntentService you created earlier.

To create a started service you need to extend the IntentService class.

public class SampleService extends IntentService

Let’s take a simple example to illustrate how this works.

In the onHandleIntent method you will add a Log.

@Override
protected void onHandleIntent(Intent intent) {
    Log.v(TAG, "In onHandleIntent. Message will be printed after 10sec");
    if (intent != null) {
        synchronized (this){
            try {
                wait(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.v(TAG, "Service started");
        }
    }
}

To call this service you will add a button to the content_main.xml file

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="center"
    android:layout_margin="15dp"
    android:id="@+id/callSampleServiceId"
    android:text="Start Service"
    android:background="@android:color/holo_blue_dark"
    android:textColor="@android:color/white"/>

On click of this button an explicit intent will be called.

if(v.getId() == R.id.callSampleServiceId){
    Log.v(TAG, "Service Button Clicked");

    Intent intent = new Intent(this, SampleService.class);
    startService(intent);
}

View the complete source code here.

Author: androidsmartly

I am a Tech Enthusiast who likes to work on new Ideas. Sharing knowledge on Android, Marketing, Startups and More.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s