Easy Tutorial
❮ Moible Web Front Source Funny Programmer Pictures ❯

10.5 AlarmManager (Alarm Service)

Category Android Basic Tutorial

Introduction to This Section:

>

This section introduces the AlarmManager in Android, which, as the name suggests, allows us to develop alarm clock apps for mobile phones. The explanation in the documentation is: it broadcasts a specified Intent for us at a particular moment. In simple terms, we set a time, and when the time comes, the AlarmManager will broadcast an Intent that we have set, such as pointing to a certain Activity or Service when the time is up! In addition, there are some important points in the official documentation:

Another point to note is that the AlarmManager is mainly used to run your code at a certain moment, even if your APP is not running at that particular time! Also, starting from API 19, the mechanism of Alarms is inexact, and the operating system will convert alarms to minimize wake-up and battery usage! Some new APIs will support strictly accurate delivery, see setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent). The targetSdkVersion will continue to use the previous behavior before API 19, and all alarms will be delivered accurately when accurate delivery is required. More details can be found in the official API documentation: AlarmManager


1. Difference between Timer class and AlarmManager class:

>

If you have studied J2SE, you are certainly not unfamiliar with Timer. Timers are essential when writing timed tasks. However, in Android, it has a shortcoming and is not very suitable for timed tasks that need to run in the background for a long time because Android devices have their own sleep strategy. When there is no operation for a long time, the device will automatically put the CPU into a sleep state, which may cause the timed tasks in the Timer to not run properly! The AlarmManager does not have this problem because it has the ability to wake up the CPU, ensuring that the CPU can work normally every time a specific task needs to be executed, or when the CPU is in a sleep state, the registered alarm will be retained (can wake up the CPU), but if the device is powered off or restarted, the alarm will be cleared! (Android phone alarm does not ring when powered off...)


2. Obtain an instance of AlarmManager:

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

3. Explanation of related methods:

>

-set (int type, long startTime, PendingIntent pi): One-time alarm

-setRepeating (int type, long startTime, long intervalTime, PendingIntent pi): Repeating alarm, different from 3, the interval time of the alarm is not fixed

-setInexactRepeating (int type, long startTime, long intervalTime, PendingIntent pi): Repeating alarm, time is not fixed

-cancel (PendingIntent pi): Cancel the AlarmManager's timing service

-getNextAlarmClock (): Get the next alarm, the return value is AlarmManager.AlarmClockInfo

-setAndAllowWhileIdle (int type, long triggerAtMillis, PendingIntent operation) Similar to the set method, this alarm is valid when the system is in low power mode

-setExact (int type, long triggerAtMillis, PendingIntent operation): Execute the alarm precisely at the specified time, which is more accurate than the set method

-setTime (long millis): Set the system wall time

-setTimeZone (String timeZone): Set the system's continuous default time zone

-setWindow (int type, long windowStartMillis, long windowLengthMillis, PendingIntent operation): Set an alarm to trigger within a given time window. Similar to set, this method allows applications to precisely control the degree to which the operating system adjusts the alarm trigger time.

Key parameter explanation :

>

-Type (Alarm type): There are five optional values: AlarmManager.ELAPSEDREALTIME: The alarm is not available when the phone is in sleep mode, and the alarm uses relative time (relative to the start of the system boot) in this state, with a state value of 3; AlarmManager.ELAPSEDREALTIMEWAKEUP The alarm will wake up the system and perform the prompt function in sleep mode, and the alarm also uses relative time in this state, with a state value of 2; AlarmManager.RTC The alarm is not available when the phone is in sleep mode, and the alarm uses absolute time, that is, the current system time, with a state value of 1; AlarmManager.RTCWAKEUP The alarm will wake up the system and perform the switch (v.getId()) { 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 Calendar c = Calendar.getInstance(); c.setTimeInMillis(System.currentTimeMillis()); // Set the Calendar object based on the user's selected time c.set(Calendar.HOUR, hourOfDay); c.set(Calendar.MINUTE, minute); // ②Set the AlarmManager to start the Activity at the time corresponding to the Calendar alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi); Log.e("HEHE", c.getTimeInMillis() + ""); // The time here is a Unix timestamp // Prompt that the alarm is set: Toast.makeText(MainActivity.this, "Alarm 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, "Alarm canceled", Toast.LENGTH_SHORT) .show(); break; }

Then there is the alarm clock page's ClockActivity.java:

/**
 * Created by Jay on 2015/10/25 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 alarm reminder dialog, click OK to close the ringtone and the page
        new AlertDialog.Builder(ClockActivity.this).setTitle("Alarm Clock").setMessage("Little pig, little pig, get up~")
                .setPositiveButton("Close Alarm", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mediaPlayer.stop();
                        ClockActivity.this.finish();
                    }
                }).show();
    }
}

The code is very simple, and the core process is as follows:

>

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

>

  1. System version or mobile phone, above 5.0 basically no hope, Xiaomi, search Baidu yourself~
  2. Is ClockActivity registered?
  3. If you use alarmManager to send a broadcast, and the broadcast activates the Activity, you need to set a flag for the Intent: i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 4.

In addition, for examples of using AlarmManager in combination with later Service to implement timed background tasks, see: 4.2.2 Advanced Service


5. Download the code example:

AlarmManagerDemo.zip


Summary of this section:

>

Well, this section explained the use of AlarmManager (alarm clock service) in Android. In addition to customizing your own alarm clock like the example, you can also combine it with Service, Thread to complete polling, etc., there are many ways to use it, and you need to explore it yourself, well, that's it for this section, thank you~

-1.0 Android Basic Tutorial

-1.0.1 The latest Android Basic Tutorial Catalog in 2015

-1.1 Background and System Architecture Analysis

-1.2 Development Environment Construction

-1.2.1 Developing Android APP with Eclipse + ADT + SDK

-1.2.2 Developing Android APP with Android Studio

-1.3 Solving SDK Update Issues

-[1.4 Gen

❮ Moible Web Front Source Funny Programmer Pictures ❯