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())) {
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 )) {
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){
MyAlarmMangerSupport.set(context);
}
[..]
}
}
}