Android IntentService With example

In the previous tutorial we have seen unbound service and bound service , in this tutorial we will see one more kind of service in android called intentserver , IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand.The IntentService is used to perform a certain task in the background. Once done, the instance of IntentService terminates itself automatically.

The intentService class provides a method onHandleIntent() which will be asynchronously called by the Android system.




XML Layout


Create a xml layout with progessbar textview and button .

file : activity_main.xml
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="15dp" >

    <Button
        android:id="@+id/bt_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="10dp"
        android:text="Button"
        android:onClick="startProgress" />

    <ProgressBar
        android:id="@+id/pb_id"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        />

    <TextView
        android:id="@+id/tv_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>


Intent Service

  1. Create a class SimpleIntentService which extends IntentService class .
  2. Override the onHandleIntent() method inside SimpleIntentService class .
  3. Inside the onHandle() Method Create an intent and set the data for intent object and send broadcast which will  be received in main activity .

file : SimpleIntentService.java
package com.pavan.intservicedemo;

import android.app.IntentService;
import android.content.Intent;
import android.os.SystemClock;
import com.pavan.intservicedemo.MainActivity.ResponseReceiver;

public class SimpleIntentService extends IntentService {

    public SimpleIntentService() {
        super("SimpleIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        // processing done here….
        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction(ResponseReceiver.ACTION_RESP);

        for (int i = 0; i <= 100; i++) {

            broadcastIntent.putExtra("per", i);
            // send broadcast
            sendBroadcast(broadcastIntent);
            // sleep
            SystemClock.sleep(100);
        }

    }
}

MainActivity

  1. Create a class MainActivity and set the content of this class with above defined xml layout.
  2. Onclick of button , startProgress() method is called inside this method start service by calling startService by passing intent as object as paramter to it.
  3. Create an Inner class ReponseReceiver and extend it to BroadcastReceiver
  4. Inside the ReponseReceiver class override the onReceive method , when broadcast is received this  method gets call , update the progress bar using Asynctask .
  5. Inside the onResume() method register broadcast .
  6. Inside the onPause() method unregister broadcast.

file : MainActivity.java
package com.pavan.intservicedemo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity {

    ProgressBar pbr;
    TextView tv;
    Button btn;

    ResponseReceiver receiver = new ResponseReceiver();

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

        pbr = (ProgressBar) findViewById(R.id.pb_id);
        tv = (TextView) findViewById(R.id.tv_id);
        btn = (Button) findViewById(R.id.bt_id);

    }

    public void startProgress(View view) {

        btn.setEnabled(false);

        Intent serviceIntent = new Intent(this, SimpleIntentService.class);
        startService(serviceIntent);
    }

    // Broadcast component
    public class ResponseReceiver extends BroadcastReceiver {
        public static final String ACTION_RESP = "com.pavan.intentservice";

        // on broadcast received
        @Override
        public void onReceive(Context context, Intent intent) {

            int value = intent.getIntExtra("per", -1);

            new Mytask().execute(value);

        }
    }

    class Mytask extends AsyncTask<Integer, Integer, Integer> {

        @Override
        protected Integer doInBackground(Integer... arg0) {

            return arg0[0];
        }

        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);

            pbr.setProgress(result);

            tv.setText(result + " % Loaded");

            if (result == 100) {
                tv.setText("Completed");
                btn.setEnabled(true);
            }

        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        registerReceiver(receiver, new IntentFilter(
                ResponseReceiver.ACTION_RESP));
    }

    @Override
    protected void onStop() {
        super.onStop();

        unregisterReceiver(receiver);
    }

}


Manifest


Declare the Service component inside the manifest file .


file : AndroidMainfest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.pavan.intservicedemo"
    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="SimpleIntentService" >
        </service>
    </application>

</manifest>



1 comment:

Moises Dominguez said...

well, you're such a great inspiration for me, thanks for making android development easier for us

Post a Comment