ZOFTINO.COM android and web dev tutorials

Android IntentService Example

If your app has long running tasks, you may need to consider implementing services to run those log running operations in the background. Service like activity is a component in android. Services can be created by extending Service class and implementing required callback methods.

Services created by extending Service class handle multiple requests concurrently and they run in the main thread. But if your requirement is that each service request be handled one at a time and in separate work thread, then the best way to create it is by extending IntentService class.

IntentService class provides framework to take care of queuing requests, executing request one at time in worker thread and stopping service when not used. In this post, I will show how to implement IntentService. If you need more information on service and want to view service examples, please visit my android services post.

How to Create & Use IntentService

You need to create service by extending IntentService and implementing onHandleIntent() method. This is the only method that needs to be implemented in most scenarios. IntentService implements and provides default behavior for callback methods such as onCreate(), onStartCommand() and onDestroy(). In case, if you need to add custom behavior to these call back methods, you can override these methods but you need to make sure that corresponding super class method is called in your implementation.

Clients can start service by calling startService method passing intent which identifies the service. Clients can call startService any number of times, but only one instance of intent service is created and all requests are queued and processed in separate work thread. Clients don’t need to worry about calling stopService, as IntentService stops itself when there are no requests to serve.

If your service needs to send information back to activity or client, service can do so by sending broadcast intent containing results as extras. Clients need to register broadcast receiver in order to listen to service broadcast events and receive results from service.

IntentService Example

IntentService

package com.zoftino.content;


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

public class CashbackIntentService extends IntentService{
    final static String CASHBACK_INFO = "cashback_info";
    public CashbackIntentService() {
        super("Cashback IntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String cb_category = intent.getStringExtra("cashback_cat");

        String cbinfo = getCashbackInfo(cb_category);
        sendCashbackInfoToClient(cbinfo);
    }
    private String getCashbackInfo(String cbcat){
        String cashback;
        if("electronics".equals(cbcat)){
            cashback = "Upto 20% cashback on electronics";
        }else if("fashion".equals(cbcat)){
            cashback = "Upto 60% cashbak on all fashion items";
        }else{
            cashback = "All other categories except fashion and electronics, flat 30% cashback";
        }
        return cashback;
    }
    private void sendCashbackInfoToClient(String msg){
        Intent intent = new Intent();
        intent.setAction(CASHBACK_INFO);
        intent.putExtra("cashback",msg);
        sendBroadcast(intent);
    }
}

Activity

package com.zoftino.content;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;


public class IntentServiceActivity extends AppCompatActivity {

    private CashbackReciver cashbackReciver;
    private TextView tv;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intentservice);

        tv = (TextView) findViewById(R.id.cb_results);
        registerCashbackReceiver();
    }
    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(cashbackReciver);
    }
    public void startCashbackService(View view){
        EditText et = (EditText) findViewById(R.id.cashback_cat);

        Intent cbIntent =  new Intent();
        cbIntent.setClass(this, CashbackIntentService.class);
        cbIntent.putExtra("cashback_cat", et.getText().toString());
        startService(cbIntent);
    }
    private void registerCashbackReceiver(){
        cashbackReciver = new CashbackReciver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(CashbackIntentService.CASHBACK_INFO);

        registerReceiver(cashbackReciver, intentFilter);
    }
    private class CashbackReciver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String cbinfo = intent.getStringExtra("cashback");
            tv.setText(cbinfo);
        }
    }

}

Activity layout xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_intent_service"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    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="com.zoftino.content.IntentServiceActivity">
    <TextView
        android:id="@+id/cb_results"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></TextView>
    <EditText
        android:id="@+id/cashback_cat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></EditText>
    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="startCashbackService"
        android:text="Get Cashback Info"></Button>
</LinearLayout>