How to test daily alarms on Android?

One of my favorite projects shows notifications of specific dates defined by the user. I use

AlarmManger.setRepeating(AlarmManager.RTC_WAKEUP, millis, AlarmManager.INTERVAL_DAY, pendingIntent)

to schedule a daily alarm that launches the app to decide if it should show a notification today.

The problem is that sometimes daily anxiety stops working. I know several reasons for this (rebooting the device, changing the date / time, reinstalling the application, dose mode), and I'm sure there are some reasons that I have not found (ideas are welcome!).

My question is how to properly test alarms against all possible risks? Are there control tests?

+4
source share
2 answers

My question is how to properly test alarms against all possible risks? Are there control tests?

Since it AlarmManageris part of the Android OS and therefore well tested, you do not need to perform any control or unit tests to verify it. You can test your services caused by an alarm, but there is no need to check whether your alarm is set correctly or not.

There are only a few situations where your alarm is discarded, invalidated or ignored. You have already called them:

  • upon reboot
  • when changing time
  • in the mode of doses

, , ( ) .


,

public class BootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
            // set repeating alarm 
            MyAlarmMangerSupport.set(context);
        }
    }
}


:

public class TimeChangeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if (Intent.ACTION_TIME_CHANGED.equals(action ) || Intent.ACTION_TIMEZONE_CHANGED.equals(action )) {
            // cancel previous alarm and set a new one
            MyAlarmMangerSupport.cancelAndSet(context);
        }
    }
}


, - , , , .

, doze - , API 23.

  • .

  • setExactAndAllowWhileIdle, Android 23 +:

    alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, period, pendingIntent);
    

    : :

    public class AlarmReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
    
            if ("my-Pet-Notification".equals(action )) {
                 if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                     // set repeating alarm, calls setExactAndAllowWhileIdle
                     MyAlarmMangerSupport.set(context);
                 }
    
                 //execute service to show notification
                 [..]
            }
        }
    }
    
+2

, / .

0

Source: https://habr.com/ru/post/1669119/


All Articles