1. Alarm Controller
Alarm is the Alarm service in Android. Allow us to regularly execute our program. The program will be awakened as long as the device is not shut down or restarted.
1.1 One Shot Alarm
The example shows sending a broadcast 30 seconds later. A prompt message is displayed after receiving the broadcast.
Intent intent = new Intent (AlarmController. this, OneShotAlarm. class );
PendingIntent sender = PendingIntent. getBroadcast (AlarmController. this,
0, intent, 0 );
// We want the alarm to go off 30 seconds from now.
Calendar calendar = Calendar. getInstance ();
Calendar. setTimeInMillis (System. currentTimeMillis ());
Calendar. add (Calendar. SECOND, 30 );
// Schedule the alarm!
AlarmManager am = (AlarmManager) getSystemService (ALARM_SERVICE );
Am. set (AlarmManager. RTC_WAKEUP, calendar. getTimeInMillis (), sender );
PendingIntent is a description of intent, which can be called after a period of time.
Use the getSystemService method to obtain AlarmManager.
The onReceive method in OneShotAlarm. java can receive this intent.
Public void onReceive (Context context, Intent intent)
{
Toast. makeText (context, R. string. one_shot_received, Toast. LENGTH_SHORT). show ();
}
1.2 Repeating Alarm
Send a broadcast every 15 seconds. A prompt message is displayed after receiving the broadcast.
Long firstTime = SystemClock. elapsedRealtime ();
FirstTime ++ = 15*1000;
AlarmManager am = (AlarmManager) getSystemService (ALARM_SERVICE );
Am. setRepeating (AlarmManager. ELAPSED_REALTIME_WAKEUP,
FirstTime, 15*1000, sender );
The SystemClock. elapsedRealtime () method gets the number of milliseconds from the boot to the present.
In the setRepeating (int type, long triggerAtTime, long interval, PendingIntent operation) method, triggerAtTime is the first execution time, and interval is the cycle interval.
Am. cancel (sender );
Stop loop execution. Www.2cto.com
2. Alarm Service
Start the service every 30 seconds.
MAlarmSender = PendingIntent. getService (AlarmService. this,
0, new Intent (AlarmService. this, AlarmService_Service.class), 0 );
Other methods are similar to the preceding method. In this example, a service is started. Generally, a service is used for a task with a long processing time.
Am. cancel (mAlarmSender );
The method for stopping is the same.