Android Project

Android Project
Android Project

Monday, November 21, 2011

Running a service in background on Android

Here the code is generate to run some process in background through service. For example we are running the time in background and displaying it in the UI. The service coding will be in a seperate class

import java.util.Date;
import; import android.content.Intent; import android.os.Handler; import android.os.IBinder; public class MyService extends Service { public static final String BROADCAST_ACTION = ""; private final Handler handler = new Handler(); Intent intent;

int counter = 0; @Override public void onCreate() { // Called on service created intent = new Intent(BROADCAST_ACTION); } @Override

public void onDestroy() { // Called on service stopped }

@Override public void onStart(Intent intent, int startid) { int i = 0; while (i < 101) { if (i > 100) { this.onDestroy(); } else { counter = i; i++; handler.removeCallbacks(sendUpdatesToUI); handler.postDelayed(sendUpdatesToUI, 1 * 1000); // 1 sec }

} } private Runnable sendUpdatesToUI = new Runnable() { public void run() { DisplayLoggingInfo(); handler.postDelayed(this, 1 * 1000); // 1 sec }

}; private void DisplayLoggingInfo() { intent.putExtra("time", new Date().toLocaleString()); intent.putExtra("counter", String.valueOf(counter)); sendBroadcast(intent); }

public static boolean isRunning() { return true; } @Override

public IBinder onBind(Intent intent) { return null; } }

So for starting the service and stopping the service we will be using

startService(new Intent(ServiceDemoActivity.this, MyService.class));
stopService(new Intent(ServiceDemoActivity.this, MyService.class));

For updating the UI we need to use the broadcast service. In that BroadcastReceiver we will update the UI

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {

}; private void updateDate(Intent intent) { String time = intent.getStringExtra("time"); TextView date = (TextView) findViewById(; date.setText(time); }
In the the method DisplayLoggingInfo() will send the broadcast to the activity to update the UI, the UI xml code is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""

 android:layout_width="fill_parent" android:id="@+id/date"
 android:layout_height="wrap_content" android:text="" android:gravity="center" android:textSize="20sp" android:padding="20dp"/>
 <Button android:id="@+id/stop" android:text="Stop Service" android:layout_width="wrap_content" android:layout_height="wrap_content" />

If we are opening the application on the first time means, it will be like this

and if we go out and come back to the page means, it will be showing a message like this

and if we stop the service means, it will be showing a message like this

You can download the full source code

Download source

Have a good day.