Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Android每天午夜在我的课堂上运行方法。_Java_Android_Scheduled Tasks_Alarmmanager - Fatal编程技术网

Java Android每天午夜在我的课堂上运行方法。

Java Android每天午夜在我的课堂上运行方法。,java,android,scheduled-tasks,alarmmanager,Java,Android,Scheduled Tasks,Alarmmanager,我在活动类中有一些方法。我每天午夜都想运行这些方法。我想在活动类中这样做: public void doStuff() { //the Date and time at which you want to execute DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = dateFormatter .parse("2012-07-06 13:05:45"); //Now cr

我在活动类中有一些方法。我每天午夜都想运行这些方法。我想在活动类中这样做:

public void doStuff() {

//the Date and time at which you want to execute
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = dateFormatter .parse("2012-07-06 13:05:45");

//Now create the time and schedule it
Timer timer = new Timer();

//Use this if you want to execute it once
timer.schedule(new MyTimeTask(), date);

//Use this if you want to execute it repeatedly
//int period = 10000;//10secs
//timer.schedule(new MyTimeTask(), date, period );
}
public static class MyTimeTask extends TimerTask
{

    public void run()
    {
        //calculate new times
        //and relaunch service

    }
}

但是作为一个静态类,我不能访问公共的方法和变量。因此,我可以使用报警管理器来执行此操作吗?我可以在哪里接收报警以便运行任务?

您可以使用报警管理器或作业调度器在午夜设置每日报警。然后,如果您需要一个活动,您的广播接收器将启动一个活动。但是没有办法让它成为旧的活动,因为没有办法保证它仍然是开放的(可能不是,Android很可能是为了资源而杀了它)@Gabeschen我不需要一个活动,但我想运行活动中的一些方法,进行一些计算,然后在后台启动一个服务。我会将这些函数分解到另一个类中,这两个类都可以共享。请记住,您的应用程序几乎肯定会停止并重新启动,因此任何数据都需要以某种形式从磁盘读取。