我創建了一個虛擬的IntentService
,它運行在前臺,基本上只記錄了它每隔5秒醒了多久。這已經在測試設備上運行了幾個小時,而不需要任何WakeLock
權限。此外,它似乎並沒有損害電池壽命。在設備上的電池狀態中,即使使用1%的電池電量也不會顯示。如何在不需要WakeLock
的情況下持續運行此服務?爲什麼我的IntentService不需要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();
}
}
一些相關的解釋http://android.stackexchange.com/questions/69693/how-do-timers-and-alarms-function-while-the-device-is-sleeping – zapl 2014-12-02 20:49:28