我目前正在尝试使用以下代码每天执行一项任务
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
}
}
}
我称这项服务为
startService(new Intent(this, BackupService.class));
如果我设置 5 分钟这样的短间隔,这工作正常,但这不适用于长间隔。如果我在 android 应用程序中运行服务,那么我可以看到我的服务处于运行状态。我认为 timertask 类可能有问题。我该如何解决我的问题??