Top Picks

January 22, 2013


How to start service to do something repeatedly in android


I am currently trying following code to perform a task on daily basis

public class BackupService extends Service { private Timer timer = new Timer(); @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show(); startBackup(); return START_STICKY; } private void startBackup() { Date date = new Date(time); System.out.println("Backup time:" +date); timer.scheduleAtFixedRate(new BackupTimerTask(), date, delayTime()); } private long delayTime() { long delay = 86400000; System.out.println("delay time:" + delay); return delay; } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); if (timer != null){ timer.cancel(); } Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show(); } private class BackupTimerTask extends TimerTask { @Override public void run() { System.out.println("Backup started"); //starting backup here } } }

and I am calling this service as

startService(new Intent(this, BackupService.class));

This is working fine if I put short interval like 5 minute, but this is not working on long inteval. And if I go to running services in android apps then i can see my service is in running state. I think probably something is wrong with timertask class. How I can solve my problem??



Actually, in Android there are no “unkillable tasks” who can be executed with 100% guarantee.
If you take a look in android lifecycle management, if the device needs resources, the system will kill some unused or old tasks running.

This is the same for android services. A service has a greater privilege as a simple task, but the service can still be killed by the system.

The problem in your case is probably that when you are setting the timer to be 5min, your service is running correctly. The problem arrives when you considerably increase the time. Then, the chance that the service will be killed is much bigger: See

So, you will have to consider another approach to acheave your goal. One of the solutions, but still without 100% guarantee, is to use foreground services:

Professional Hosting fro Just Host

Filed under: Android Coding FAQ



No Comments

Leave a reply