2014-12-01 68 views
1

我創建了一個虛擬的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(); 
    } 

} 
+1

一些相關的解釋http://android.stackexchange.com/questions/69693/how-do-timers-and-alarms-function-while-the-device-is-sleeping – zapl 2014-12-02 20:49:28

回答

2

你實際提供的定時數據也顯示,該設備作爲一個整體進入休眠狀態。您撥打sleep()的電話會讓您的Service的當前線路休眠至少5秒鐘。調度程序通常在這些類型的操作上爲+/- 10ms。如果沒有喚醒鎖,整個系統將會睡眠,這對您的服務生命週期沒有影響。設備上的其他設備正在喚醒系統(可能是網絡事件,鬧鐘,其他服務等),這又會導致您的應用在下次睡眠之前安排好。事實上,您的服務是一個前景,最大限度地降低了由於資源不足而導致死亡的風險,但是並沒有做任何事情來防止系統處理低功率。

+0

如果系統進入睡眠時,我的線程處於5秒睡眠的中間,系統一旦喚醒就會繼續執行。例如,如果我的線程睡了3秒鐘,那麼設備進入休眠狀態,當它醒來時,它會再睡2秒鐘? – Richard 2014-12-08 00:22:26

+0

不,在那一刻睡眠時間已經過期。 – 2014-12-08 02:01:23

+0

由於以下原因,我不知道這是否屬實。最初,我讓自己的線程睡了一個小時,然後記錄睡眠時間。我發現,即使幾個小時後,睡眠時間也不會被記錄下來。它讓我覺得該設備需要至少一個小時才能成功記錄。意思是說,一個小時並不僅僅需要在現實世界中的時間,而是設備必須清醒一小時才能在記錄之前成功達到分配的睡眠時間。那有意義嗎? – Richard 2014-12-08 02:12:33

相關問題