Implementation of Android Timing Lock Screen (Alarm Manager Timing Part)

The Story of Newbies Entering the Pit

Keyword: Alarm Manager

Introduction to Alarm Manager:

Reference website:
Reference website:

Recommend this website:

Understand android Low Power Consumption Mode:
Role of Alarm Manager: Broadcast a specified Intent for us at a specific time.
Namely: Set a time by yourself, when the system time arrives at this time, Alarm Manager automatically broadcasts an Intent we have set, pointing to an Activity or Service.
Note: Alarm Manager is mainly used to run your code at a certain time, even if your APP does not run at that particular time.

2. Obtain the AlarmManager instance object:
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

3. Methods:

SetExact (int type, long start time, Pending Intent pi); one-time alarm clock, precise execution time, for accurate alarm clock

Parametric Interpretation: This section refers to the website

4. Programming:

(1) Type type

Alarm Manager.RTC: The alarm clock is unavailable during sleep, in which absolute time (current system time) is used and the state value is 1.

(2) Start Time

Since the time obtained through SP is String type, it needs to be converted to long type first, and the time unit is ms.

 1 /**
 2      * String Type conversion to date type
 3      * strTime: The time for the string type to be converted,
 4      * formatType: The format yyyy-MM-dd HH:mm:ss to be converted
 5      * //yyyy MM, dd, HH, mm minutes, ss seconds.
 6      * strTime The time format must be the same as formatType's.
 7      */
 8     public static Date stringToDate(String strTime, String formatType){
 9         KLog.d("Get into stringToDate");
10         try {
11             SimpleDateFormat formatter = new SimpleDateFormat(formatType);
12             Date date = null;
13             date = formatter.parse(strTime);
14             return date;
15         }catch (Exception e){
16             return null;
17         }
18     }
19     /**
20      * String Converting type to long type
21      * .............................
22      * strTime For String type time to be converted
23      * formatType Time format
24      * formatType The format is yyyy-MM-dd HH:mm:ss//yyyy year MM month DD day HH hour mm minute SS second
25      * strTime The time format of formatType and formatType must be the same
26      */
27     public static long stringToLong (String strTime,String formatType){
28         KLog.d("Get into stringToLong");
29         try{
30             //String Type conversion to date type
31             Date date = stringToDate(strTime, formatType);
32             Log.d(TAG,"call stringToDate()Acquired date: " + date);
33             if (date == null) {
34                 return 0;
35             }else {
36                 //date Type Conversion long type
37                 long Hour = date.getHours();
38                 long Min = date.getMinutes();
39                 long TimeLong = Hour*60*60*1000 + Min*60*1000;
40                 Log.d(TAG,"stringToLong()Acquired Hour: " + Hour + " h");
41                 Log.d(TAG,"stringToLong()Acquired Min: " + Min + " min");
42                 Log.d(TAG,"stringToLong()Acquired TimeLong: " + TimeLong + " ms");
43                 return TimeLong;
44             }
45         }catch (Exception e){
46             return 0;
47         }
48     }


Conversion among Java Date, String and Long date types

Reference website:

After successful acquisition of sleep time (SLEEP_TIME) and wake-up time (GET_UP_TIME) (unit ms), calculate the screen-locked time IntervalTime (sleep time to wake-up time):


1         //Calculate time intervals
2         if (GET_UP_TIME >= SLEEP_TIME){
3              IntervalTime = GET_UP_TIME - SLEEP_TIME;
4         }else {
5              IntervalTime = 24*60*60*1000 + GET_UP_TIME - SLEEP_TIME;
6         }

(3) Define the operation of jump Activity: Pending Intent pi

Our goal is to use AlarmManager's set() method to enable the alarm clock to perform our custom intent operation at a specified time point. The setting of time points is very important here. If the setting of time is not accurate (generally accurate to seconds, the following code is accurate to ms), the alarm clock will be delayed in executing intent. (SLEEP_TIME_HOUR and SLEP_TIME_MIN distributions are hours and minutes of sleep time)


 1 //Set the current time
 2 Calendar calendar = Calendar.getInstance();
 3 calendar.setTimeInMillis(System.currentTimeMillis());
 4 //Set according to the time selected by the user Calender Object (i.e. sleeping time)
 5 calendar.set(Calendar.HOUR_OF_DAY, (int)SLEEP_TIME_HOUR);
 6 calendar.set(Calendar.MINUTE, (int) SLEEP_TIME_MIN);
 7 calendar.set(Calendar.SECOND, 0);
 8 calendar.set(Calendar.MILLISECOND,0);
 9 //Set the current time zone (if the time zone is wrong, the alarm clock will be biased)
10 TimeZone timeZone = TimeZone.getDefault();//Obtaining System Time Zone
11 KLog.d("The time zone currently set is: " + timeZone);
12 calendar.setTimeZone(timeZone);
13 KLog.d("Sack time:" + SLEEP_TIME + "ms, Wake-up time:" + GET_UP_TIME + "ms.");
14 KLog.d("Night rest time: IntervalTime = " + IntervalTime + "ms.");

Define intent operations:


1         //Define to jump to LockScreenActivity.class Medium Intent object intent
2         Intent intent = new Intent(RobotClientMainActivity.this, LockScreenActivity.class);
3         intent.putExtra("INTERVAL", IntervalTime);


Put Extra ("INTERVAL", IntervalTime); "INTERVAL" is the keyword, and IntervalTime is the incoming value (here refers to the time ms when the screen is locked during sleep). Skip to LockScreenActivity.class with value, and LockScreenActivity performs the corresponding lock screen operation.

Initialize the execution pi of the alarm clock:

Use of Pending Intent.getActivity:

1 //Initialize the execution of the alarm clock pi
2 pi = PendingIntent.getActivity(RobotClientMainActivity.this,0

Method: Pending Intent. getActivity (Context context, int request Code, Intent intent, int flags);

The first parameter is context.

The second parameter is the request code, which identifies the object of the Pending Intent, equivalent to a keyword.

The third parameter is intent, which is used to jump Activity.

The fourth parameter represents four different states of Pending Intent, which can be understood as state identifiers. The four states are as follows:


If the same Pending Intent object already exists in the current system, the existing Pending Intent will be cancelled and a Pending Intent object will be regenerated.


If the same Pending Intent object does not exist in the current system, the system will not create the Pending Intent object, but will return null directly.


The Pending Intent only works once. After the Pending Intent object is triggered by the send() method, Pending Intent will automatically call cancel() to destroy it. If you call send() method again, the system will return a SendIntentException.


If the system has a Pending Intent equivalent to the Pending Intent you describe, the system will use the Pending Intent object, but will use a new Intent to update the Intent object data in Pending Intent, such as Extras in Intent.

(4) Setting up alarm manager:

1 //Definition AlarmManager object
2     private AlarmManager alarmManager;
1         //Initialization alarmManager
2         alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
1         /**
2          * Set Alarm Manager to start Activity at Calendar time
3          * Skip to LockScreen Activity to perform lock screen operation when bedtime arrives.
4          */
5         alarmManager.setExact(AlarmManager.RTC,calendar.getTimeInMillis(),pi);
6         KLog.d("from calender Reading sleep time:" + calendar.getTime()
7                 + "/n Millisecond:"+calendar.getTimeInMillis());

Here, the system has been able to jump to the lock screen operation at a specified time. But the problem in practice is: as long as the system time has exceeded the specified time, when the shutdown and restart will automatically jump into the lock screen operation - why??.... :(...) Seek guidance from God


Although the mechanism of alarmManager.setExact has not been clarified, the function has been successfully realized by adding if/else judgment at the critical time point, using its performance in practice (indicating that the screen will still be locked after the lock time is restarted).

The relevant conditions are as follows:

Definition and initialization:

1  //Define sleep and wake-up time units ms
2         long SLEEP_TIME,GET_UP_TIME;
3         //Hours and minutes corresponding to sleeping and waking hours
6         //Define the interval between bedtime and wake-up time
7         long IntervalTime;
8         //Define the current time (unit) of the system ms)
9         long CurrentTime_ms;
1 //Set the current time
2         Calendar calendar = Calendar.getInstance();
3         calendar.setTimeInMillis(System.currentTimeMillis());
4         KLog.d("111 The current system time is:" + calendar.getTime());
5         KLog.d("System current time Hour: " + calendar.get(Calendar.HOUR_OF_DAY));
6         KLog.d("System current time Min: " + calendar.get(Calendar.MINUTE));
7         KLog.d("System current time Second: " + calendar.get(Calendar.SECOND));
8         CurrentTime_ms = calendar.get(Calendar.HOUR_OF_DAY)*60*60*1000
9                 +calendar.get(Calendar.MINUTE)*60*1000+calendar.get(Calendar.SECOND)*1000;

Conditional judgment:

 1  /**
 2          * Calculate the length of night rest
 3          * If the current time does not reach the sleep time, the rest time is set as the sleep time to wake up time.
 4          * If the current time is between sleep time and wake-up time, the rest time is set between the current time and wake-up time.
 5          */
 6         if (GET_UP_TIME >= SLEEP_TIME) {
 7             if ((CurrentTime_ms >= SLEEP_TIME) && (CurrentTime_ms <= GET_UP_TIME)) {
 8                 IntervalTime = GET_UP_TIME - CurrentTime_ms;
10             }else {
11                 IntervalTime = GET_UP_TIME - SLEEP_TIME;
12             }
13         }else {
14             if ((CurrentTime_ms <= SLEEP_TIME) && (CurrentTime_ms >= GET_UP_TIME)) {
15                 IntervalTime = 24*60*60*1000 + GET_UP_TIME - SLEEP_TIME;
16             }else {
17                 if(CurrentTime_ms <= GET_UP_TIME) {
18                     IntervalTime = GET_UP_TIME - CurrentTime_ms;
19                 }else {
20                     IntervalTime = 24*60*60*1000 + GET_UP_TIME - CurrentTime_ms;
21                 }
22             }
23         }
24         KLog.d("Night rest time: IntervalTime = " + IntervalTime + "ms.");
 1 /**
 2          * Set Alarm Manager to start Activity at Calendar time
 3          * Skip to LockScreen Activity to perform lock screen operation when bedtime arrives.
 4          * If the current time of the system does not belong to the night rest time, add judgment so that the program no longer calls alarmManager.
 5          */
 6         if (GET_UP_TIME >= SLEEP_TIME) {
 7             if (CurrentTime_ms < GET_UP_TIME) {
 8                 KLog.d("current time CurrentTime_ms = " + CurrentTime_ms + "ms");
 9                 KLog.d("Wake-up time GET_UP_TIME = " + GET_UP_TIME + "ms");
10                 alarmManager.setExact(AlarmManager.RTC,calendar.getTimeInMillis(),pi);
11                 KLog.d("from calender Reading sleep time:" + calendar.getTime()
12                         + "/n Millisecond:"+calendar.getTimeInMillis());
13             }
14         }else {
15             KLog.d("current time CurrentTime_ms = " + CurrentTime_ms + "ms");
16             KLog.d("Wake-up time GET_UP_TIME = " + GET_UP_TIME + "ms");
17             alarmManager.setExact(AlarmManager.RTC,calendar.getTimeInMillis(),pi);
18             KLog.d("from calender Reading sleep time:" + calendar.getTime()
19                     + "/n Millisecond:"+calendar.getTimeInMillis());
20         }

Function: APP lock screen can be restarted within the specified time range, and the whole lock screen activity will not be terminated because of restart.

Summary: After consulting N multi-materials, I finally realized this function (*^ ^*). Although there are still many things I don't understand, I will continue to work hard.

Finally, the gods give their opinions...

Tags: Android REST Google Programming

Posted on Fri, 09 Aug 2019 05:05:13 -0700 by B.Murali Krishna