In this tutorial about
Need some career advice or prepping for an Android developer interview? Hit me up on Topmate.io, and let's chat!
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.
Difference between Intent and IntentService
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.
But It’ll be really annoying if after every minute WhatsApp prompts us that it’s checking if the message is received or is the user typing…, So for such things we use IntentService.
Android IntentService 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 mom) or do some other task.
Learn how to style a Custom Spinner for Android App. Read more here.
So how to implement such great ability in our app?
As told above, its all done in the background ?❤ 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
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
Files Created:
- AndroidManifest.xml
- activity_main.xml
- MainActivity.Java
- AndroidDvlprIntentService.Java
Getting Started
First, let’s create an empty project with a blank launcher activity and then Go to Java Folder and create a new Java file named, ‘AndroidDvlprIntentService.java‘
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 AndroidDvlprIntentService(String name) {
super(name);
}
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 AndroidDvlprIntentService() {
super("AndroidDvlprIntentService");
}
Again press Alt + Enter and insert an Override method which is onHandleIntent() method.
In this tutorial, we are going to pass a Log message in the console using IntentService so for this create a Log Tag named
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Log.i( TAG ,"Service Commenced!");
}
The complete code for AndroidDvlprIntentService.Java is here:
package com.androiddvlpr.intentservicedemo;
import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.util.Log;
/**
* Created by androiddvlpr on 31-05-2019.
*/
public class AndroidDvlprIntentService extends IntentService {
public static final String TAG = "intentservicedemo";
public AndroidDvlprIntentService() {
super("AndroidDvlprIntentService");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Log.i( TAG ,"Service Commenced!");
}
}
Working on MainActivity
In MainActivity.Java we will call this onHandleIntent() method in onCreate() method using Intent and start service. Using code:
Intent intent = new Intent(this, AndroidDvlprIntentService.class);
startService(intent);
The complete code for MainActivity.Java is here:
package com.androiddvlpr.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, AndroidDvlprIntentService.class);
startService(intent);
}
}
Always remember to declare your services in AndroidMainfest.xml file, So the code for this will be as follows:
<service android:name=".AndroidDvlprIntentService"/>
The complete code for AndroidMainfest.xml file is here:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androiddvlpr.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=".AndroidDvlprIntentService"/>
</application>
</manifest>
There is no need to edit activity_main.xml file for this tutorial.
Save and Run your Project and check for the result in the Console as shown below. Don’t forget to use ‘
Interested in knowing how to clear user memory before running your own background task?Learn more from here.
WhatsApp example Source Code to get User Last Location
In the following Android IntentService Example, we have provided with
WhatsApp Background Service.java
package com.androiddvlpr.intentservice;
import android.annotation.SuppressLint;
import android.app.IntentService;
import android.content.Intent;
import android.location.Location;
import static android.provider.UserDictionary.Words.APP_ID;
public class WhatsAppBackgroundService extends IntentService {
private GoogleApiClient googleApiClient;
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public WhatsAppBackgroundService(String name) {
super(name);
}
@Override
protected void onHandleIntent(Intent intent) {
googleApiClient = new GoogleApiClient.Builder(this, this, this).addApi(LocationServices.API).build();
Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
double lat = lastLocation.getLatitude(), lon = lastLocation.getLongitude();
String units = "imperial";
@SuppressLint("DefaultLocale") String url = String.format("http://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&units=%s&appid=%s",
lat, lon, units, APP_ID);
new GetWeatherTask(textView).execute(url);
}
@Override
public void onStart( Intent intent, int startId) {
super.onStart(intent, startId);
if (googleApiClient != null) {
googleApiClient.connect();
}
}
@Override
public boolean stopService(Intent name) {
if (googleApiClient != null) {
googleApiClient.disconnect();
}
return super.stopService(name);
}
}
MainActivity.java
package com.androiddvlpr.intentservice;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import org.jetbrains.annotations.NotNull;
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_ACCESS_COARSE_LOCATION = 123;
private GoogleApiClient googleApiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_COARSE_LOCATION },
PERMISSION_ACCESS_COARSE_LOCATION);
} else {
Intent intent = new Intent(this, WhatsAppBackgroundService.class);
startService(intent);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NotNull String[] permissions, @NotNull int[] grantResults) {
if (requestCode == PERMISSION_ACCESS_COARSE_LOCATION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// All good!
} else {
Toast.makeText(this, "Need your location!", Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onStart() {
super.onStart();
if (googleApiClient != null) {
googleApiClient.connect();
}
}
@Override
protected void onStop() {
if (googleApiClient != null) {
googleApiClient.disconnect();
}
super.onStop();
}
}
In case if you’ve any further doubt to be clear, please share in the comment section below.
1 comment