在我的应用程序中,我有一项服务。它在主要活动开始时启动并执行以下操作:
timer.scheduleAtFixedRate (
new TimerTask() {
public void run() {
appendToFile("diff: "+(System.currentTimeMillis()-lastTime));
lastTime = System.currentTimeMillis();
}
}, 0, 1);
基本上,它会创建一个Timer
,每毫秒更新一次。在每次更新时,计时器会查看上次调用的时间,并保存计时器调用文件之间的时间。由于系统总是存在开销,我希望输出的每一行都超过1毫秒,也许大约10毫秒。
这是应用程序睡着时的一个特色。
diff: 6
diff: 8
diff: 5
diff: 81
diff: 12
diff: 12
diff: 54
diff: 60
diff: 5734
diff: 77
diff: 9
diff: 20
diff: 6
diff: 21
diff: 10
diff: 13
diff: 16895
diff: 13
diff: 82
diff: 269
diff: 35
diff: 25
diff: 24
diff: 20
diff: 30
diff: 26
diff: 11
diff: 14
diff: 49
diff: 57
diff: 9
我的问题是我有时会得到一些奇怪的结果。中间的16895表示由于某种原因,服务在系统空闲时等待将近17秒才能运行其任务。但是,之后直接显示10到30毫秒之间的更正常结果。我知道这是在系统休眠期间,因为日志中有更多条目。该服务从未被销毁,因为我也记录了对onDestroy()
的所有呼叫。
有没有解释为什么服务会突然暂停?有没有办法可以确保它一直在运行?
答案 0 :(得分:2)
就像你说的那样,系统正在睡觉。当服务从内存中取出时,服务被“销毁”。睡眠系统只是暂时的暂停,因为它会在CPU唤醒后立即恢复。
您可以使用AlarmManager唤醒系统,这将在特定时间安排偶数发生。它会唤醒系统。您还可以使用wake lock yourself or use a WakefulBroadcastReceiver来保持CPU运行。
请注意,保持CPU运行是一个很大的电池消耗,因此只有在您绝对需要时才能节省使用它。