Skip to main content

Android IntentService Example Included Tutorial – Faultinmycode

In this tutorial about Android IntentService example is taken from a well know messaging app Whatsapp in which IntentService is used to help its user stick around with app and stay connect with their friends.

In the world of Android App Development, we code majorly to set up connections. These connections are not only between the components of our app and the user itself but also with other apps present in the Android OS.

For example, if I am viewing some website on Google Chrome and if I happen to click on some mailto link on the website, this would invoke Google Chrome to open Gmail or some other Emailing App to send a message to that email address.



android intentservice example
android intentservice example


This method of calling another app from one app is done using something known as intent. The intent is asynchronous messages that allow application components to request some additional functionality from some other Android App. However, IntentService isn’t something same as Intent but the intent is used to start or call IntentService.

Whereas Service is an application component of Android that is used to perform long running tasks in the background and IntentService is the base class of Service which means it helps in the creation of other class that can reuse the code implicitly inherited from the base class. 

IntentService provides a mechanism for your app to run a long running task in the background. For example like we have Whatsapp installed on our mobile phone and through WhatsApp, we exchange messages and have amazing conversations with our friends and family members (sometimes with annoying bosses too!)

Now this app needs to check whether or not the user or your friend on the other end has sent the message or not, for which it needs to stay connected to its servers through the internet. Now it’ll be really annoying if after every minute WhatsApp prompts us that its checking if the message is received or is the user typing…, So for such things we use IntentService which is a long-running task in the background that’ll help Whatsapp to check in the background without any user prompt or action that whether the user on the other end is typing or has sent the message.

One great thing about IntentService is this that it doesn’t even needs the app to be active in Foreground to run the service. It automatically runs in the background and prompts the user about new message from a friend (or enemy) or do some other task.

So how to implement such great ability in our app? Lets code!

As told above, its all done in the background (:P) one doesn’t need to worry about thread creation or management. Just create a class extend it to IntentService class and implement the long-running task in onHandleIntentMethod() and to trigger this method use Intent.

The Intent will spawn a worker thread for the extended class and call the onHandleIntent() method on this thread. Now on this thread, the long running task which is like checking for new messages in the background will be carried.

And don’t worry as this will not disturb or block the main thread so you can continue sending the message to your some other or the same friend or run some other app.
Getting on to our Tutorial part using Steps below.

Android IntentService Example

In this step by step tutorial about Android IntentService example is taken in which an Android app is created from scratch and IntentService is called while starting the app in the console using MainActivity in under onCreate() method using Intent.

Learn how to create your own Piano Android App here or Calculator app over here.

Files Created:

  1. AndroidManifest.xml
  2. activity_main.xml
  3. MainActivity.Java
  4. FaultinmycodeIntent.Java

Steps for Tutorial:

1.Open Android Studio (we are using Android Studio version 3.x here)

2. Create a new project named IntentService Demo with empty activity.

android intentservice example
android intentservice example


3. Go to Java Folder and create a new Java file named, ‘FaultinmycodeIntent’.

4. Extend this Java class to IntentService and implement Constructor by pressing Alt + Enter for Windows. It’ll leave you with the code as shown below:
public FaultinmycodeIntent(String name) {
    super(name);
}
 
5. Remove the String as we won’t be passing any arguments here and instead of name write name of this class in the super method.

public FaultinmycodeIntent() {
    super("FaultinmycodeIntent");
}
 
6. Again press Alt + Enter and insert an Override method which is onHandleIntent() method.

7. In this tutorial, we are going to pass a Log message in the console using IntentService so for this create a Log Tag named intentservicedemo and pass this in onHandleIntent() method.

@Override
protected void onHandleIntent(@Nullable Intent intent) {

    Log.i( TAG ,"Service Commenced!");

}
 
8. The complete code for FaultinmycodeIntent.Java is here:

FaultinmycodeIntent.Java
package com.faultinmycode.intentservicedemo;

import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * Created by risha on 16-12-2017.
 */

public class FaultinmycodeIntent extends IntentService {


    public static final String TAG = "intentservicedemo";

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

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {

        Log.i( TAG ,"Service Commenced!");

    }
}
 
9. In MainActivity.Java we will call this onHandleIntent() method in onCreate() method using Intent and start service. Using code:

Intent intent = new Intent(this, FaultinmycodeIntent.class);
startService(intent);
 
10. The complete code for MainActivity.Java is here:

MainActivity.Java
package com.faultinmycode.intentservicedemo;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent(this, FaultinmycodeIntent.class);
        startService(intent);


    }

}
 
11. Always remember to declare your services in AndroidMainfest.xml file, So the code for this will be as follows:

<service android:name=".FaultinmycodeIntent"/>
 
12. The complete code for AndroidMainfest.xml file is here:

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

    <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=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>
 
13. There is no need to edit activity_main.xml file for this tutorial.

14.Save and Run your Project and check for the result in the Console as shown below. Don’t forget to use ‘intentservicedemo’ as the filter in the console.

android intentservice example
android intentservice example

In case if you’ve any further doubt to be clear, please share in the comment section below. You can access complete tutorials series for Android Development here for Free! Click here to know more.

Comments

Popular posts from this blog

How To Open PDF File in Android Application Example Included

Want to know How To Open PDF File in Android Application Example. To open a PDF File in Android Application, your app can take help from Free Android library available on Github.

Here are few apps made from PDF Library you can look at, click here to know more.

By using Android Library you are not only leveraging the hard work from another developer but also making it easier and quicker to develop an android app.
How To Open PDF File in Android Application Example  In this tutorial series, we will teach you how to open a pdf file in Android Application Example included with the help of Android PDFViewer library developed by Barteksc.

Get inspirtion from here: Top 7 PDF Download for Mobile Android Apps

Before I proceed further, here is the screenshot of the kind of PDF Viewer that’ll be created using Android Studio.



 How To Open PDF File in Android Application Example

The app will open a specified pdf file which will be copied in the assets folder of your Android studio project. I'v…

Python Turtle Example: Flappy Bird Development in under 10 mins!

Python Turtle Example | Develop Flappy Bird Clone in 10 mins In the following tutorial, we have used following Python libraries:
1. random: To generate obstacles at random position. 2. turtle: To help provide directions to the player. 3. vector from freegames: To 2-dimensional vectors.
Before developing the game, here is a screenshot of what you'll be developing in 10 mins.
Steps to create Python Flappy Bird Game:
1. Open Pycharm and install 'freegames' package by going to Files > Settings > Project Interpreter. 2. Click on '+' sign on right and search for 'freegames' package. 3. Import packages in your project by writing following lines of code:
from random import * from turtle import * from freegames import vector 4. There are two variables required in the game, one for Bird object and another for an array of obstacles:
bird = vector(0, 0) balls = []
5. Create function for the player response on screen tap:
def tap(x, y): "Move bird up in res…

Open Weather Map API Example | Create Android Weather App

In this tutorial blog, using open weather map API example, we will create an Android weather app. The Android App will able to access Open weather map website server and access weather details of particular location.

The App will look similar to the image shown below. It will fetch real time weather of the location provided in MainActivity.Java file.


Software / Files used:Android Studio (Version 3.x) Files Edited / Created:activity_main.xmlMainActivity.JavaWeather.JavaAndroidManifest.xml Steps Involved in Open Weather Map API Example: Here are the Steps you need to follow on ‘Open Weather map API Example’ to create Android Weather App:

1. Open the Open Weather map API link provided here. Sign up for Current Weather Data API key here.

2. Once the key is received, save it to notepad or on stick notes.

3. Open Android Studio and create a new Project with name, ‘FIMC Weather App’, we will select an empty activity in the wizard and wait for Gradle build.



4. Open AndroidManifest.xml…