How To Start IntentService In Android

When you start an android service in android’s 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 ways to run child thread in the android service object.

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

1. What Is Android IntentService.

  1. Android intent service is a background service that executes it’s code in a child thread.
  2. You can extend the android.app.IntentService to implement it.
  3. Your custom intent service class must override the onHandleIntent(Intent intent) method, this method will be invoked when intent service is called. You can extract action, extra input data 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 clicking the first button, it will start a common background service.
  3. In that service’s onStartCommand method, it will create a child thread and print thread info when the child thread runs.
  4. When clicking the second button, it will start an android IntentService object. It will print that object’s thread info in the onHandleIntent method.
  5. You can see the different child threads id, names in the android Logcat monitor console like below.
    android-intentservice-child-thread-info

3. Android IntentService Example Source Code.

  1. There are 4 java files in this android IntentService example.
    android-intentservice-example-file-structure

3.1 Main Activity.

  1. 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.

  1. 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.

  1. 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.

  1. ThreadUtil.java
    package com.dev2qa.example.service.intentService;
    
    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.

  1. 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.

  1. 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>

1 thought on “How To Start IntentService In Android”

  1. Why each time I push the button is called the onDestroy method? this means that the intent service is not already running as soon as its launch?

Leave a Comment

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.