gpt4 book ai didi

java - 如何启动服务在android中重复做某事

转载 作者:太空宇宙 更新时间:2023-11-03 13:30:08 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Android regular task (cronjob equivalent)

我目前正在尝试按照代码每天执行一项任务

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 类可能有问题。我该如何解决我的问题??

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com