如何使用报警管理计划任务如何使用、任务、计划

2023-09-05 09:04:05 作者:【深拥你】

我是新来的Andr​​oid。我在一个应用程序的工作中,我需要计划将在未来被执行的任务。

I am new to Android. I am working on an App in which I need to schedule a task that will be performed in future.

我看了一下AlarmManager和了解,以我们能够做到这一点使用AlarmManager。

I have read about AlarmManager and get to know to that we can accomplish this using AlarmManager.

谁能告诉我一些教程或任何来源在哪里可以得到的东西。

Can anyone please tell me about some tutorial or any source where can I get the things.

推荐答案

内容摘自博客Scheduling任务在Android中使用报警管理器

public void scheduleAlarm(View v)
{
    // The time at which the alarm will be scheduled. Here the alarm is scheduled for 1 day from the current time. 
    // We fetch the current time in milliseconds and add 1 day's time
    // i.e. 24*60*60*1000 = 86,400,000 milliseconds in a day.       
    Long time = new GregorianCalendar().getTimeInMillis()+24*60*60*1000;

    // Create an Intent and set the class that will execute when the Alarm triggers. Here we have
    // specified AlarmReceiver in the Intent. The onReceive() method of this class will execute when the broadcast from your alarm is received.
    Intent intentAlarm = new Intent(this, AlarmReceiver.class);

    // Get the Alarm Service.
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    // Set the alarm for a particular time.
    alarmManager.set(AlarmManager.RTC_WAKEUP, time, PendingIntent.getBroadcast(this, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
    Toast.makeText(this, "Alarm Scheduled for Tommrrow", Toast.LENGTH_LONG).show();       
}

AlarmReceiver类

public class AlarmReceiver extends BroadcastReceiver
{
     @Override
     public void onReceive(Context context, Intent intent)
     {

         // Your code to execute when the alarm triggers
         // and the broadcast is received.   

     }
}