Possible Duplicate:
Android regular task (cronjob equivalent)
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??
Milos makes some good points, but please don’t make your service a Foreground service. Instead, use AlarmManager. There are several related issues that you can take a look at:
Android AlarmManager – Scheduling a recurring Intent to fire off twice a day
AlarmManager not working
etc…