我创建了一个虚拟的IntentService,它在前台运行,实际上只是记录每5秒唤醒了多长时间。它已经在测试设备上运行了几个小时,不需要任何WakeLock权限。此外,它似乎丝毫没有损害电池寿命。在设备的电池电量统计中,即使使用了1%的电池也不会出现。无需WakeLock,该服务如何连续运行?

更新:从中我注意到一些有趣的行为。似乎该服务实际上正在休眠,但是在相当不一致的基础上。回顾一些日志语句,您可以看到,即使线程仅睡眠5秒钟,然后醒来,系统似乎正在暂停服务。请注意,时间从17:56:31跳到17:56:54到17:57:05。跳23秒,然后跳9秒。解释为什么这样做会很有帮助。谢谢。

12-01 17:56:31.479    8723-8780/com.example.timedrift D/Done Sleeping﹕ Active for 2375000 Seconds
12-01 17:56:54.630    8723-8780/com.example.timedrift D/Done Sleeping﹕ Active for 2380000 Seconds
12-01 17:57:05.632    8723-8780/com.example.timedrift D/Done Sleeping﹕ Active for 2385000 Seconds
12-01 17:57:11.097    8723-8780/com.example.timedrift D/Done Sleeping﹕ Active for 2390000 Seconds
12-01 17:57:16.098    8723-8780/com.example.timedrift D/Done Sleeping﹕ Active for 2395000 Seconds
12-01 17:58:00.829    8723-8780/com.example.timedrift D/Done Sleeping﹕ Active for 2400000 Seconds


IntentService:

@Override
protected void onHandleIntent(Intent intent) {

    Notification notification = new Notification(R.drawable.ic_launcher, "Time",
            System.currentTimeMillis());
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    notification.setLatestEventInfo(this, "Time",
            "Time", pendingIntent);
    startForeground(100, notification);

    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = sharedPrefs.edit();

    try {
        Log.d("TimerService", "Start");
        int i = 1;
        while(true){
            Thread.sleep(5000);
            int numberOfSeconds = i++*5;
            Log.d("Done Sleeping", String.valueOf("Active for "+numberOfSeconds+" Seconds"));
            editor.putLong(String.valueOf(numberOfSeconds), numberOfSeconds);
            editor.apply();
        }


    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

最佳答案

您提供的时序数据实际上确实表明该设备总体上将进入睡眠状态。您对sleep()的调用正在使您当前的Service线程休眠至少5秒钟。在这些类型的操作上,调度程序通常为+/- 10ms。没有唤醒锁,整个系统将进入睡眠状态,这不会影响您的服务生命周期。设备上的其他东西正在唤醒系统(可能是网络事件,警报,其他服务等),这又导致您的应用在下次睡眠之前被安排了时间。您的服务是前台服务这一事实可以最大程度地减少由于资源不足而导致服务被杀死的风险,但是它并不能阻止系统的低功耗处理。

关于android - 为什么我的IntentService不需要WakeLock?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27237850/

10-15 22:36