Android : IntentService - The saviour

Android is very large in terms of understanding its concept and implementing it to the application development. When we develop real world application which we do in most cases we need to understand Android Platform behaviour and its functionality properly other wise we will end up in developing an App which user can reject in a very first use (Which is considered to be the wow moment) and it possible for the user either to reject the app usage for the future purpose and only 20% of those user come back to the app even if it retain that wow factor.

While working on such app its very much important to Developer that User should not get disturbed while using the app and also the functionality of the app should work in proper way so that desired smooth functionality can be achieved. One of the task while developing android application is Making Network call to the server and after fetching data displaying it to the user UI.

In many cases we directly call the network API in our Android Component Activity or in Fragment which is good starting practice but not good for a great application. Our application is running on Main thread of the system and we all know we can’t make a network call on the main thread we need a background thread for this and in most cases we use AsyncTask Thread and while writing this post I am pretty much sure that you guys must know about this Class very much even if you have developed a very simple server call based application.

AsyncTask is great option for the network call and very handy to use we get total of 5 methods from the AsyncTask class

1. onPreExecute() : This is the first method makes calls with our implementation and this method runs on the main thread . In most cases we use this method to show the progress bar to user while making calls to the server.

2. doInBackground() : This method runs on the background thread and mainly contains the functionality to talk to server with giving input and taking response from it. (Never try to put the response in the UI in this method itself as our UI component works on main thread and if you are chaining it here it will cause to Crash your app).

3.onProgressUpdate() : This is also runs on the main thread, Main used to show the progress of the task that is going on in doInBackgroudn() method to the user.

4.onPastExecute() : This method runs on the Main thread also and we perform the resultant UI change task in this function after getting response from the server.

5.onCancel() : This method called up when in any case the request is being canceled.

From above note we can see that only doInBackground() method runs on the background thread after everything is running on the main thread which causes to wait to the user untill and unless the task is completed. What if the task which you are executing in this taking too much of time for example if you have to upload a image file to the server which is large in size and your internet connection is slow.

Another Scenario can be possible if you are developing a mail based client application and whenever user had to send a mail to anyone he had to wait until the mail is either is received or either get failed due to some error.

** Also you can use each instance of AsyncTask calss only once. **

In such cases Service can be very helpful and let us to develop a very fine and grained application for the user. Also a service can perform its task when the application is not in foreground state. Any long running operation that we are performing should always go Service with a new thread.

So we know with combination of Service and Thread we can perform are many of the hazel task in background and user can be free to either use application as usual or even can leave the application and move to another one.

Combination of Service and Thread is so great that Google had implemented it its API and it is called IntentService. IntenetSerivice is mainly combination of Service and Handler thread. So we don’t need to reinvent the wheel of service extending Handler thread again and again. All you have to do is extend your call to IntentService.

Following is the raw implementation of IntentService.

public class ServiceWithHandler extends IntentSerivce {
/*
Implementation of the service
}

When you extend your Java Class with IntentService it will let you to implement method named as onHandleIntent(Intent intent), which will handle the intents which will be given to the service while starting it.

Following raw code is an example in which try to either upload a Bitmap file to server or send a Message to any one with given address.

public class ServiceWithHandler extends IntentService {// Action Name you define for the Intent received in the service for intent //filter
private static final String ACTION_UPLOAD_PHOTO = “com.service.help.upload.photo”;
private static final String ACTION_SEND_MESSAGE = “com.service.help.send.message”;
// Extra message constant that you pass in the intent while starting the //service
private static final String ACTION_EXTRA_MESSAGE = “extra_message_constant”;
private static final String MESSAGE_TO_SEND = “message”;
private static final String MESSAGE_RECEIVER = “receiver”;
private static final String MESSAGE_SENDER = “sender”;
// This is String class object but you need to send the Bitmap class object so //that it can be
// uploaded on the server using this KEY
private static final String UPLOAD_PHOTO = “bitmapPhoto”;
public ServiceWithHandler(String name) {
super(name);
// You don’t want your service to redeliver its process if in any case phone //shutdown and application get started
// If you require such action you can set it to true
setIntentRedelivery(false);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
// Getting the Action of the Intent
String intentAction = intent.getAction();
// Comparing the action that you received in the onHandleIntent class
if (ACTION_UPLOAD_PHOTO.equals(intentAction)) {
Bitmap photo = intent.getParcelableExtra(UPLOAD_PHOTO);Toast.makeText(this, “Upload Photo”, Toast.LENGTH_SHORT).show();uploadPhotoToServer(photo);} else if (ACTION_SEND_MESSAGE.equals(intentAction)) {Toast.makeText(this, “Send Message”, Toast.LENGTH_SHORT).show();
String sender_name_or_emailAddress = intent.getStringExtra(MESSAGE_SENDER);
String receiver_name = intent.getStringExtra(MESSAGE_RECEIVER);
String message = intent.getStringExtra(MESSAGE_TO_SEND);
Toast.makeText(this, “Send Message to” + receiver_name, Toast.LENGTH_SHORT).show();sendMessage(sender_name_or_emailAddress, receiver_name, message);
}
}private void uploadPhotoToServer(Bitmap photo) {// You can start network call to upload photo to server here
}
private void sendMessage(String sender_name_or_emailAddress, String receiver_name, String message) {// You can start network call here and send the message via using network //call
}
}

You can simply start this service with startService() method from Activity with actions and extras. If you call this Service multiple time then it will queued up by the internal Handler which you don’t have to be bother about this Handler also ensures about all the request is completed also only one request will be called at any given time. You don’t even have to worry about stoping this service as IntenService are designed in such a manner that when all the task is completed it will automatically non-functional state before that it will be in started state.

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade