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

By | July 14, 2012

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.

3 thoughts on “How to make a http call repeatedly from a service in android?

  1. Pingback: RSS Feeds im Hintergrund laden - Android-Hilfe.de

Leave a Reply

Your email address will not be published. Required fields are marked *