Basic Android tutorial-10.5 AlarmManager (alarm clock service)

Source: Internet
Author: User

Basic Android tutorial-10.5 AlarmManager (alarm clock service)
Basic Android tutorial-10.5 AlarmManager (alarm clock service)

Tags (separated by spaces): basic Android tutorial

This section introduces:

The AlarmManager (alarm clock service) in Android is introduced in this section. You can use it to develop an alarm clock APP,
The explanation in this document is: broadcast a specified Intent for us at a specific time. Simply put, we set a time by ourselves,
Then, when the time is reached, AlarmManager will broadcast a set Intent for us. For example, when the time is reached, it can point to
Activity or Service! Note the following in the official documents:

In addition, AlarmManager is mainly used to run your code at a specific time point.
Time is not running! Also, since API 19, the Alarm mechanism is inaccurate, and the operating system will change the Alarm clock.
To minimize wake-up and battery usage! Some new APIs support strict and accurate transfer. For more information, see
SetWindow (int, long, long, PendingIntent) and setExact (int, long, PendingIntent ).
TargetSdkVersion before API 19, the application will continue to use previous behaviors. All alarms must be accurately transmitted.
Will be passed. For more details, see the official API documentation AlarmManager.

1. Differences between Timer class and AlarmManager class:

If you have learned J2SE, you are certainly not familiar with Timer. Timer, generally when writing scheduled tasks
But in Android, he has a short board, which is not suitable for those running in the background for a long time.
Scheduled task. Because the Android device has its own sleep policy, the device automatically enters the CPU
Sleep Status, which may cause the scheduled tasks in the Timer to fail to run normally! AlarmManager does not exist.
In this case, because it has the CPU wake-up function, it can ensure that the CPU can work normally every time a specific task needs to be executed,
Or when the CPU is sleeping, the registered alarm will be retained (the CPU can be awakened), but if the device is disabled or re-
If it is enabled, the alarm will be cleared! (The Android phone shuts down and the alarm does not sound ...)

2. Obtain the AlarmManager instance object:
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
3. Related methods:
Set(Int type, long startTime, PendingIntent pi): one-time alarm SetRepeating(Int type, long startTime, long intervalTime, PendingIntent pi ):
Recurrence alarm, which is different from 3. The interval of 3 alarm is not fixed. SetInexactRepeating(Int type, long startTime, long intervalTime, PendingIntent pi ):
Repetitive alarm, time not fixed Cancel(PendingIntent pi): cancels the scheduled service of AlarmManager. GetNextAlarmClock(): Get the next alarm. The returned value is AlarmManager. AlarmClockInfo. SetAndAllowWhileIdle(Int type, long triggerAtMillis, PendingIntent operation)
Similar to the set method, this alarm is effective when the system is in low-power mode. SetExact(Int type, long triggerAtMillis, PendingIntent operation ):
The precise execution of the alarm clock at the specified time is more accurate than that set by the set method. SetTime(Long millis): set the time on the system wall. SetTimeZone(String timeZone): sets the default time zone for system persistence. SetWindow(Int type, long windowStartMillis, long windowLengthMillis, PendingIntent operation ):
Set an alarm to trigger at a given time window. Similar to set, This method allows applications to precisely control operating system calls.
The trigger time of the entire alarm.

Key parameters:

Type(Alarm type ):
There are five optional values:
AlarmManager. ELAPSED_REALTIME:
The alarm is unavailable when the mobile phone is sleeping. In this status, the relative time (relative to the start of the system) of the alarm is used. The status value is 3;
AlarmManager. ELAPSED_REALTIME_WAKEUP
When the alarm is in sleep state, the system is awakened and a prompt function is executed. In this state, the relative time is also used, and the status value is 2;
AlarmManager. RTC
The alarm is not available in sleep state. In this state, the absolute time of the alarm is used, that is, the current system time. The status value is 1;
AlarmManager. RTC_WAKEUP
It indicates that the system is awakened when the alarm is sleeping and the prompt function is executed. In this status, the absolute time of the alarm is used and the status value is 0;
AlarmManager. POWER_OFF_WAKEUP
It indicates that the alarm notification function can be performed normally when the phone is shut down. Therefore, it is one of the most frequently used statuses in the five states. In this status, the alarm is also set to an absolute time with A status value of 4; however, this status seems to be affected by the SDK version, which is not supported by some versions; StartTime: The first execution time of the alarm, in milliseconds. The time can be customized, but the current time is generally used.
Note that this attribute is closely related to the first attribute (type). If the alarm clock corresponding to the first parameter uses relative time
(ELAPSED_REALTIME and ELAPSED_REALTIME_WAKEUP), the relative time must be used for this attribute.
(Relative to the system startup time). For example, the current time is represented as SystemClock. elapsedRealtime ();
If the alarm corresponding to the first parameter uses absolute time (RTC, RTC_WAKEUP, POWER_OFF_WAKEUP ),
This attribute requires absolute time. For example, the current time is System. currentTimeMillis (). IntervalTime: Indicates the interval between two alarms, in milliseconds. PendingIntent: It is bound to the execution action of the alarm, such as sending a broadcast and giving a prompt.
PendingIntent is the encapsulation class of Intent. It should be noted that if the alarm is triggered by starting the service, the PendingIntent object should be obtained using Pending. getService.
(Context c, int I, Intent intent, int j) method; if it is broadcast to implement the alarm
If prompted, The PendingIntent object should be obtained using PendingIntent. getBroadcast
(Context c, int I, Intent intent, int j) method.
If the alarm is prompted, The PendingIntent object should be obtained
PendingIntent. getActivity (Context c, int I, Intent intent, int j) method.
If these three methods are used incorrectly, although no error is reported, the alarm is not displayed.
4. Example: A simple scheduled task

This example is only applicable to Android 4.4 or lower systems, but not to Android 5.0 or later.
The above AlarmManager solution will be added later! In addition, the set method may be inaccurate.
You can use setExtra () to set AlarmManager more accurately!

Run:

Implementation Code:

First, a simple layout file:Activity_main.xmlCreate a raw folder in res and drop the audio file!
Create an outer LayoutActivity_clock.xmlActivity layout when an alarm is triggered! No things.


  
   
  

NextMainActivity. javaIt is also very simple:

Public class MainActivity extends AppCompatActivity implements View. onClickListener {private Button btn_set; private Button btn_cancel; private AlarmManager alarmManager; private PendingIntent pi; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); bindViews ();} private void bindViews () {btn_set = (Button) find ViewById (R. id. btn_set); btn_cancel = (Button) findViewById (R. id. btn_cancel); alarmManager = (AlarmManager) getSystemService (ALARM_SERVICE); Intent intent = new Intent (MainActivity. this, ClockActivity. class); pi = PendingIntent. getActivity (MainActivity. this, 0, intent, 0); btn_set.setOnClickListener (this); btn_cancel.setOnClickListener (this) ;}@ Override public void onClick (View v) {switch (v. getI D () {case R. id. btn_set: Calendar currentTime = Calendar. getInstance (); new TimePickerDialog (MainActivity. this, 0, new TimePickerDialog. onTimeSetListener () {@ Override public void onTimeSet (TimePicker view, int hourOfDay, int minute) {// set the current time to Calendar c = Calendar. getInstance (); c. setTimeInMillis (System. currentTimeMillis (); // sets the Calendar Object Based on the time selected by the user. set (Calendar. HOUR, hourOfDay); c. set (Calend Ar. MINUTE, minute); // ② set AlarmManager to start Activity alarmManager at the corresponding time of the Calendar. set (AlarmManager. RTC_WAKEUP, c. getTimeInMillis (), pi); Log. e (HEHE, c. getTimeInMillis () +); // The time here is a unix timestamp // the alarm is set to Toast. makeText (MainActivity. this: the alarm is set ~ + C. getTimeInMillis (), Toast. LENGTH_SHORT ). show () ;}, currentTime. get (Calendar. HOUR_OF_DAY), currentTime. get (Calendar. MINUTE), false ). show (); btn_cancel.setVisibility (View. VISIBLE); break; case R. id. btn_cancel: alarmManager. cancel (pi); btn_cancel.setVisibility (View. GONE); Toast. makeText (MainActivity. this, the alarm is canceled, Toast. LENGTH_SHORT ). show (); break ;}}}

Then the alarm pageClockActivity. java:

/*** Created by Jay on 0025. */public class ClockActivity extends AppCompatActivity {private MediaPlayer mediaPlayer; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_clock); mediaPlayer = mediaPlayer. create (this, R. raw. pig); mediaPlayer. start (); // create an alert dialog box. Click OK to close the alert and the new AlertDialog page. builder (ClockActivi Ty. this). setTitle (alarm clock). setMessage (Piglet gets up quickly ~) . SetPositiveButton (disable the alarm, new DialogInterface. onClickListener () {@ Override public void onClick (DialogInterface dialog, int which) {mediaPlayer. stop (); ClockActivity. this. finish ();}}). show ();}}

The code is very simple. The core process is as follows:

AlarmManager alarmManager = (AlarmManager) getSystemService (ALARM_SERVICE );
Obtain the AlarmManager service objects provided by the system. Intent sets the component to be started:
Intent intent = new Intent (MainActivity. this, ClockActivity. class ); PendingIntent object setting action, start Activity or Service, or broadcast!
PendingIntent pi = PendingIntent. getActivity (MainActivity. this, 0, intent, 0 ); Call the set () method of AlarmManager to set the alarm type, start time, And PendingIntent object of a single alarm!
AlarmManager. set (AlarmManager. RTC_WAKEUP, c. getTimeInMillis (), pi );

In addition, if the alarm is invalid, you can start from these aspects:

1. The system version or mobile phone number above 5.0 is basically useless. Xiaomi, Baidu on its own ~
2. Is ClockActivity registered?
3. If you use alarmManager to send a broadcast and then activate the Activity, you need to set a flag for Intent:
I. setFlags (Intent. FLAG_ACTIVITY_NEW_TASK );
4.
Are there any mistakes in these places ~ Do not write getActivity as getService ~

In addition, the example of implementing scheduled background tasks by AlarmManager combined with later services is as follows:
Basic Android tutorial -- 4.2.2 advanced Service

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.