How to start a service doing something repeatedly in android… here is a solution to the problem.
How to start a service doing something repeatedly in android
Possible Duplicate:
Android regular task (cronjob equivalent)
I’m currently trying to perform a task per day following the code
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
}
}
}
I call this service
startService(new Intent(this, BackupService.class));
If I set a short interval like 5 minutes, this works fine, but it doesn’t work for long intervals. If I run the service in an Android application, then I can see that my service is running. I think there might be something wrong with the timertask class. How do I solve my problem?