How To Keep An Android Service Running

How to keep an Android service running? This is kind of a trick question as the best practice is to not keep an Android service running. If you need to have something done continuously by your app via a service, the service should be started by an AlarmManager at a regular interval and kills itself after the task is done. The reason for this is that a long running service on Android is up to the OS to determine priority and in some cases would stop running. By using this methodology, you are treading lightly since the service does not stay in memory.

Here is some sample code.

Service implementation

public class HeartBeat extends Service {

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onStart(Intent i, int startId) {

		this.beat.run();
		this.stopSelf();
	}

	public Runnable beat = new Runnable() {

		public void run() {
                    // Do something
		}
	};
}

The AlarmManager that starts it.


			Intent iHeartBeatService = new Intent(this, HeartBeat.class);
			PendingIntent piHeartBeatService = PendingIntent.getService(this, 0, iHeartBeatService, PendingIntent.FLAG_UPDATE_CURRENT);
			AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
			alarmManager.cancel(piHeartBeatService);
			alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000, piHeartBeatService);

Now the heartbeat service will start every second and do something and kill itself.

2 thoughts on “How To Keep An Android Service Running”

    1. But for detecting incoming call what to do?because wavelock takes too much battery.and when screen is off service is paused by os.

Leave a Reply

Your email address will not be published.