回覆列表
  • 1 # 使用者8303015863383

    android 一直執行的後臺服務是不存在的,而且也不是最佳實踐,因為一直執行的後臺服務會耗費大量系統資源,影響其他程式的響應從而影響到使用者體驗。題主問的是如何讓後臺服務一直執行,我認為只有系統自帶的應用或者定製的系統應用才可以有這麼高的優先順序可以保持後臺服務一直執行。如果是在非root的系統上的普通應用,只能是透過一些方法,讓使用者覺著後臺服務一直執行。比如,監聽開機事件,顯式地啟動後臺服務;啟動後臺服務後給它設定“前臺執行”的優先順序;定時任務來檢查後臺服務是否在執行,不執行的話重新啟動它。可以考慮使用如下幾種方案來達到一直執行的效果。1. 呼叫startForeground方法,android: Service vs SingleTop Activity moved to background2. 使用AlarmManager 傳送定時任務 : Diamonds Are Forever. Services Are Not.更極端的例子,如果應用被幹掉了,定時任務(AlarmManager)這種方法確實不管用了,但是可以考慮給後臺服務設定“前臺”執行的優先順序這種方法。比如音樂播放器,在啟動播放服務後,通知欄會顯示一個播放進度的通知條,這個通知條是必須的,因為透過它才能使後臺服務獲取到“前臺”執行的優先順序從而避免被系統幹掉。這種做法也是官方推薦的做法。下面是官方文件中的一些具體說明:說明一

    A started service can use the startForeground(int, Notification) API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory. (It is still theoretically possible for the service to be killed under extreme memory pressure from the current foreground application, but in practice this should not be a concern.)

    說明二Service | Android Developers(int, android.app.Notification)Make this service run in the foreground, supplying the ongoing notification to be shown to the user while in this state. By default services are background, meaning that if the system needs to kill them to reclaim more memory (such as to display a large page in a web browser), they can be killed without too much harm. You can set this flag if killing your service would be disruptive to the user, such as if your service is performing background music playback, so the user would notice if their music stopped playing.其他參考資料使用startForeground讓android服務前臺執行android - startForeground() without showing notification

  • 中秋節和大豐收的關聯?
  • 亞馬遜上的UPC,ASIN,EAN,GCID到底是什麼鬼?