• Android:关于定时任务重启之后的问题研究


    背景:在设置应用添加一个定时项,定时切换多用户,重启手机之后也要能响应定时切换,以及每天都能在同样的时间定时切换。
    目前现象是:正常定时,能实现定时切换;重启之后不能响应定时切换,查看定时任务也没看到相关的任务存在了。且不能每天进行定时切换。

    先查重启后无法定时切换的问题:Alarmmanager在关机重启之后还有效吗?
    adb shell dumpsys alarm>alarm.txt
    用命令打印出定时唤醒的相关信息,如下:

    RTC_WAKEUP #4: Alarm{cc9f20 type 0 origWhen 1655258820000 whenElapsed 68888312 com.android.settings}
          tag=*walarm*:action_alarm_start
          type=RTC_WAKEUP origWhen=2022-06-15 10:07:00.000 window=+18h0m0s0ms repeatInterval=86400000 count=0 flags=0x8
          policyWhenElapsed: requester=+1m28s854ms app_standby=-22s133ms device_idle=-- battery_saver=--
          whenElapsed=+1m28s854ms maxWhenElapsed=+18h1m28s854ms
          operation=PendingIntent{25bb0d9: PendingIntentRecord{3edf156 com.android.settings startService}}
    RTC_WAKEUP #5: Alarm{1c29a9e type 0 origWhen 1655259060000 whenElapsed 69128311 com.android.settings}
          tag=*walarm*:action_alarm_end
          type=RTC_WAKEUP origWhen=2022-06-15 10:11:00.000 window=+18h0m0s0ms repeatInterval=86400000 count=0 flags=0x8
          policyWhenElapsed: requester=+5m28s853ms app_standby=-11s631ms device_idle=-- battery_saver=--
          whenElapsed=+5m28s853ms maxWhenElapsed=+18h5m28s853ms
          operation=PendingIntent{f2c297f: PendingIntentRecord{278f1ad com.android.settings startService}}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    从打印的信息可知道我的定时任务是什么类型,通过启动了服务来执行定时时间到之后的任务;
    我发现重启之后,这两项定时任务都消失了,没了;
    应该就是重启之后进程被杀掉,于是定时任务也被清除了;
    我采用的方案是:在开机接收到开机广播之后,重新添加定时任务,来达到解决重启后定时失效的问题。

    另一个问题,不能每天都响应定时,是我设置的定时任务的方法,本身就是只能一次性使用,我之前只求更精准定时,就使用了setExactAndAllowWhileIdle;

    am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, getTime(context,0), pendingIntentStart);
    
    • 1

    所以之后我就更换成:

    am.setRepeating(AlarmManager.RTC_WAKEUP, getTime(context,0), AlarmManager.INTERVAL_DAY, pendingIntentStart);
    //根据AlarmManager.INTERVAL_DAY参数来设置不同的时间。
    
    • 1
    • 2

    具体区别可以详细查看博客。

  • 相关阅读:
    必知必会打包工具tsup原理解析
    Spring Security 如何实现身份认证和授权?
    Verilog 之并行,数据类型,操作符号等相关基础归纳
    OFDI分国家/省份/行业-对外直接投资流量&存量-面板数据
    私有云NAS千万别用铁威马TNAS,不管是用群晖还是其他私有云都可能比这个好
    android四大组件:Service(初涉)
    【前端】搭建 Vite + P5.js 项目
    centos/windows服务器,Mysql数据库表结构损坏-已解决
    C#进阶04——委托和事件
    Ubuntu添加非root用户到Docker用户组
  • 原文地址:https://blog.csdn.net/chan_fan/article/details/125389308