Category Archives: Services

What are the main differences between a service and an Intent Service and when you should use it?

Service is a base class of service implementation. Service class is run in the application’s main thread which may reduce the application performance. Thus, IntentService, which is a direct subclass of Service is borned to make things easier. The IntentService is used to perform a certain task in the background. Once done, the instance of IntentService terminate itself automatically. Examples for its usage would be to download a certain resources from the Internet.

Differences

Service class uses the application’s main thread, while IntentService creates a worker thread and uses that thread to run the service.

IntentService creates a queue that passes one intent at a time to onHandleIntent(). Thus, implementing a multi-thread should be made by extending Service class directly. Service class needs a manual stop using stopSelf(). Meanwhile, IntentService automatically stops itself when there is no intent in queue.

IntentService implements onBind() that returns null. This means that the IntentService can not be bound by default.

IntentService implements onStartCommand() that sends Intent to queue and to onHandleIntent(). In brief, there are only two things to do to use IntentService. Firstly, to implement the constructor. And secondly, to implement onHandleIntent(). For other callback methods, the super is needed to be called so that it can be tracked properly.

In short
A Service is a broader implementation for the developer to set up background operations, while an IntentService is useful for “fire and forget” operations, taking care of background Thread creation and cleanup.

From the docs:

Service A Service is an application component representing either an application’s desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.

IntentService IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

How to find your Google Plus ID

This is so simple

1. Go to your Google + account (https://plus.google.com/).

2. Click on the Profile icon on the Left.

3. If you look at the URL in the address bar, it should look something like this:

https://plus.google.com/104653270154306099169/posts

4. The long numerical string in the URL is your Google+ ID. Here is CoderzHeaven’s from the URL above:

104653270154306099169/

Google + CoderzHeaven

How to make a http call repeatedly from a service in android?

We may have applications in which we may have to make repeated calls to a webservice. At that time services may be useful.

This is such an example in which we will be creating a Service in android to create a repeated call to a webservice in a time delay of some seconds or milliseconds.

OK We will start.

First We will create a new android project named “AcessWebFromService” and in the main java file copy this code.

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class AcessWebFromServiceDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        startService(new Intent(AcessWebFromServiceDemo.this, MyService.class));
    }
}

You may be getting some errors after this. Now we will clear all the errors.

Now create another class and name it “MyService.java“. This is our Service file that extends Android Service.

Paste this code into this file .

package com.coderzheaven.pack;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

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

public class MyService extends Service{
	
	private static String TAG = MyService.class.getSimpleName();
	private MyThread mythread;
	public boolean isRunning = false;
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		Log.d(TAG, "onCreate");		
		mythread  = new MyThread();
	}

	@Override
	public synchronized void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "onDestroy");
		if(!isRunning){
			mythread.interrupt();
			mythread.stop();
		}		
	}

	@Override
	public synchronized void onStart(Intent intent, int startId) {
		super.onStart(intent, startId); 
		Log.d(TAG, "onStart");
		if(!isRunning){
			mythread.start();
			isRunning = true;
		}
	}
	
	public void readWebPage(){
          HttpClient client = new DefaultHttpClient();
          HttpGet request = new HttpGet("http://google.com");
          // Get the response
          ResponseHandler<String> responseHandler = new BasicResponseHandler();
          String response_str = null;
		  try {
			 response_str = client.execute(request, responseHandler);
			 if(!response_str.equalsIgnoreCase("")){
				 Log.d(TAG, "Got Response");
			 }
		  } catch (Exception e) {
			 e.printStackTrace();
		  }
	}
	
	class MyThread extends Thread{
		static final long DELAY = 3000;
		@Override
		public void run(){			
			while(isRunning){
				Log.d(TAG,"Running");
				try {					
					readWebPage();
					Thread.sleep(DELAY);
				} catch (InterruptedException e) {
					isRunning = false;
					e.printStackTrace();
				}
			}
		}
		
	}

}

We have called this service to start running in the main java file using this code.

startService(new Intent(AcessWebFromServiceDemo.this, MyService.class));

Now the important thing is for this service to run we have to declare it in the AndroidManifest file.

This is how the AndroidManifest file looks.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.coderzheaven.pack"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AcessWebFromServiceDemo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <service android:name=".MyService"></service>

    </application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest> 

OK Now you are done. When you run this application you can see the Log coming every three seconds in the LogCat. PLease make sure that you have internet connection in the Emulator or Device.

This is how the Log looks in the Logcat.

Service

Please leave your valuable comments on this post and also share it by hitting a plus(+1) button.