How To Start IntentService In Android

When you start an android service in activity, the service runs in the activity main thread. If the service is time consuming, then the main thread will be blocked. So we had better start a child thread in the service object, this can make your activity execute smoothly.

There are two way to run child thread in android service object.

  1. Start a thread manually when android service execute. But do not forget call stopSelf() method to stop the service manually when the child thread execute finished.
  2. Make your android service object extends android.app.IntentService, IntentService will start and manage the child thread automatically for you when you start it.

1.What Is Android IntentService.

Android intent service is a background service which execute it’s code in a child thread. You can extends android.app.IntentService to implement it.

Your custom intent service class must override onHandleIntent(Intent intent) method, this method will be invoked when intent service is called. You can extract action, extra input data etc from the intent input parameter.

2. Android IntentService Example.

how to start intentservice in android

2.1 Example Execute Sequence.

  1. The example will print the activity main thread info in it’s onCreate method when the activity started.
  2. When click the first button, it will start a common background service. In that service’s onStartCommand method, it will create a child thread and print thread info when child thread run.
  3. When click the second button, it will start an android IntentService object. It will print that object’s thread info in onHandleIntent method.
  4. You can see the different child thread from id, name in android logcat monitor console.
    android intentservice child thread info
READ :   Android Button With Image And Text Example

3. Android IntentService Example Source Code.

android intentservice example file structure

3.1 Main Activity.

MyIntentServiceActivity.java

package com.dev2qa.example.service.intentService;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.dev2qa.example.R;

public class MyIntentServiceActivity extends AppCompatActivity {

    public static final String TAG_INTENT_SERVICE = "TAG_INTENT_SERVICE";

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

        setTitle("dev2qa.com - Android IntentService Example.");

        // Get activity main thread.
        Thread currThread = Thread.currentThread();

        // Get main thread info.
        String threadInfo = ThreadUtil.getThreadInfo(currThread);

        // Log main thread info.
        Log.d(TAG_INTENT_SERVICE, "Activity main thread info. " + threadInfo);

        // Click this button to start background service which start a child thread manually.
        Button startServiceWithChildThread = (Button)findViewById(R.id.intent_service_start_child_thread);
        startServiceWithChildThread.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyIntentServiceActivity.this, MyCommonService.class);
                startService(intent);
            }
        });

        // Click this button to start a intent service.
        Button startIntentService = (Button)findViewById(R.id.intent_service_start_intent_service);
        startIntentService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyIntentServiceActivity.this, MyIntentService.class);
                startService(intent);
            }
        });

    }
}

3.2 Custom Intent Service.

MyIntentService.java

package com.dev2qa.example.service.intentService;

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

public class MyIntentService extends IntentService {

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

    // Invoked when this intent service is started.
    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            // Get current child thread.
            Thread currThread = Thread.currentThread();
            // Get current thread info.
            String threadInfo = ThreadUtil.getThreadInfo(currThread);
            // Log current thread info.
            Log.d(MyIntentServiceActivity.TAG_INTENT_SERVICE, "MyIntentService child thread info." + threadInfo);
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(MyIntentServiceActivity.TAG_INTENT_SERVICE, "MyIntentService onCreate() method is invoked.");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(MyIntentServiceActivity.TAG_INTENT_SERVICE, "MyIntentService onDestroy() method is invoked.");
    }
}

3.3 Custom Common Background Service.

MyCommonService.java

package com.dev2qa.example.service.intentService;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyCommonService extends Service {

    public MyCommonService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    // Invoked when the service is started.
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //Create a child thread.
        Thread childThread = new Thread()
        {
            @Override
            public void run() {
                try {
                    Thread currThread = Thread.currentThread();

                    currThread.sleep(1000);

                    String currThreadInfo = ThreadUtil.getThreadInfo(currThread);

                    Log.d(MyIntentServiceActivity.TAG_INTENT_SERVICE, "MyCommonService child thread info. " + currThreadInfo);

                    // Invoke below method to stop the background service manually.
                    stopSelf();
                }catch(InterruptedException ex)
                {
                    Log.e(MyIntentServiceActivity.TAG_INTENT_SERVICE, ex.getMessage(), ex);
                }
            }
        };

        // Start the child thread.
        childThread.start();

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(MyIntentServiceActivity.TAG_INTENT_SERVICE, "MyCommonService onCreate() method is invoked.");
    }

    @Override
    public void onDestroy() {
        Log.d(MyIntentServiceActivity.TAG_INTENT_SERVICE, "MyCommonService onDestroy() method is invoked.");
    }
}

3.4 Thread Util Class.

ThreadUtil.java

package com.dev2qa.example.service.intentService;

/**
 * Created by Jerry on 3/9/2018.
 */

public class ThreadUtil {

    // Return thread info data include thread id, name and priority.
    public static String getThreadInfo(Thread thread)
    {
        long threadId = thread.getId();
        String threadName = thread.getName();
        int threadPriority = thread.getPriority();

        StringBuffer buffer = new StringBuffer();
        buffer.append(" id = ");
        buffer.append(threadId);
        buffer.append(" , name = ");
        buffer.append(threadName);
        buffer.append(" , priority = ");
        buffer.append(threadPriority);

        return buffer.toString();
    }
}

3.5 Layout Xml File.

activity_my_intent_service.xml

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <Button
        android:id="@+id/intent_service_start_child_thread"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start Background Service With Child Thread"/>

    <Button
        android:id="@+id/intent_service_start_intent_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start IntentService"/>
</LinearLayout>

3.6 Android Manifest Xml.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.dev2qa.example">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        
        <activity android:name=".service.intentService.MyIntentServiceActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".service.intentService.MyIntentService"
            android:exported="false" />

        <service
            android:name=".service.intentService.MyCommonService"
            android:enabled="true"
            android:exported="true"></service>
    </application>

</manifest>
(Visited 240 times, 2 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.