My question is how to test alarms properly against all possible risks? Do instrumentation tests fit here?
由于AlarmManager是Android操作系统的一部分,因此经过充分测试,您无需进行任何仪器测试或单元测试即可对其进行测试.您可以测试由警报调用的服务,但无需测试您的警报设置是否正确.
只有少数情况下您的警报被删除,无效或被忽略.你已经打电话给他们:
>重启时
>按时更改
>打瞌睡模式
现在您可以做的是使用系统通知(OS广播)重新配置警报.
On reboot
设备关闭时会报警,因此请在重启时再次设置
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);
}
}
}
On doze mode
我相信如果设备输入the doze mode,则无需显示任何不相关的通知
无论如何,即使设备处于打瞌睡状态,也有一种方法可以发出警报.
重要的是要知道,打盹模式是从API级别23开始的新功能.
>用户必须为您的应用程序whitelist your app and disable Battery Optimization.
>使用setExactAndAllowWhileIdle方法为Android级别2??3的设备设置警报:
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
[..]
}
}
}