Android 6.0 Doze模式下的Alarm Manager问题

Fil*_*eOS 8 android alarmmanager android-alarms android-pendingintent android-doze-and-standby

我制作的应用程序一直有效,直到Android 6.0.我认为这是Doze功能,它不允许我的警报发射.

我使用sharedpreferences来处理选项:

//ENABLE NIGHT MODE TIMER
    int sHour = blockerTimerPreferences.getInt("sHour", 00);
    int sMinute = blockerTimerPreferences.getInt("sMinute", 00);

    Calendar sTime = Calendar.getInstance();
    sTime.set(Calendar.HOUR_OF_DAY, sHour);
    sTime.set(Calendar.MINUTE, sMinute);

    Intent enableTimer = new Intent(context, CallReceiver.class);
    enableTimer.putExtra("activate", true);
    PendingIntent startingTimer = PendingIntent.getBroadcast(context, 11002233, enableTimer, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager sAlarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    sAlarm.setRepeating(AlarmManager.RTC_WAKEUP,
            sTime.getTimeInMillis(),
            AlarmManager.INTERVAL_DAY, startingTimer);
Run Code Online (Sandbox Code Playgroud)

这里有什么错误吗?

这是一个阻止通话的应用.谢谢!

编辑: 我有3个文件(更多但是......)像:

MainActivity (All code)
CallReceiver (Broadcast that triggers the alarm again (reboot etc))
CallReceiverService (Handles the call / phone state)
Run Code Online (Sandbox Code Playgroud)

xia*_*omi 14

打盹模式会将警报延迟到下一个维护窗口.要避免打盹模式阻止您的闹钟,您可以使用setAndAllowWhileIdle(),setExactAndAllowWhileIdle()setAlarmClock().您将有大约10秒来执行您的代码,并设置您的下一个警报(_AndAllowWhileIdle虽然方法不是每15分钟一次)

如果要测试打盹模式,可以使用ADB命令:

  1. 使用Android 6.0(API级别23)或更高版本的系统映像配置硬件设备或虚拟设备.

  2. 将设备连接到开发计算机并安装应用程序.

  3. 运行您的应用并将其保持活动状态.
  4. 关闭设备屏幕.(应用程序保持活动状态.)通过运行以下命令强制系统在打盹模式下循环:

    adb shell dumpsys battery unplug

    adb shell dumpsys deviceidle step

  5. 您可能需要多次运行第二个命令.重复此过程,直到设备状态变为空闲.

  6. 重新激活设备后,请观察应用程序的行为.当设备退出打盹时,请确保应用程序正常恢复.

编辑:添加setAlarmClock示例

别忘了检查SDK级别(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)

AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, MyAlarmReceiver.class); //or just new Intent() for implicit intent 
//set action to know this come from the alarm clock
intent.setAction("from.alarm.clock");
PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//Alarm fire in 5s.
am.setAlarmClock(new AlarmManager.AlarmClockInfo(System.currentTimeMillis() + 5000, pi), pi);
Run Code Online (Sandbox Code Playgroud)