Android Service 啟動服務

2021-08-26 17:33:12 字數 718 閱讀 3223

你能夠通過把乙個intent物件(指定要啟動的服務)傳遞給startservice()方法,從乙個activity或其他的應用程式元件啟動服務。android系統呼叫服務的onstartcommand()方法,並且給它傳遞intent物件(你不應該直接呼叫onstartcommand()方法)

例如,乙個activity能夠使用帶有明確的intent物件的startservice()方法來啟動乙個服務:

intent intent = new intent(this, helloservice.class);

startservice(intent);

startservice()方法立即返回,並且android系統呼叫服務的onstartcommand()方法。如果服務還沒有執行,系統首先呼叫oncreate()方法,然後呼叫onstartcommand()方法。

如果服務不支援繫結,那麼永startservice()方法傳送intent物件是應用程式元件和服務之間僅有的通訊模式。但是,你想要服務傳送乙個反饋結果,那麼啟動服務的客戶端可以建立乙個用於廣播的pendingintent物件(用getbroadcast()方法),並且把它傳送給啟動服務的intent物件所在的服務。然後這個服務就能夠使用這個廣播物件來傳送結果。

多個啟動服務的結果在多個對應的呼叫這個服務的onstartcommand()方法中,但是只要有乙個請求終止服務(使用stopself()方法或stopservice()方法),服務就需要被終止。

Android Service簡單總結

分兩種 local service 不少人又稱之為 本地服務 是指client service同處於乙個程序 remote service 又稱之為 遠端服務 一般是指service處於單獨的乙個程序中 remote service 常用的有兩種實現 messenger 信使 使用廣播通訊,serv...

Android Service相關知識

public void oncreate l.d wmodel.time,oncreate耗時 system.currenttimemillis s1 public static string getprocessname context cxt,int pid if procinfo.pid pi...

Android Service 終止服務

被啟動型別的服務必須管理它自己的生命週期。也就是說除非系統要 系統記憶體,否則系統不會終止或銷毀這個服務,在onstartcommand 方法返回後,這個服務會繼續執行。因此而這種型別的服務必須通過呼叫stopself 方法或另乙個元件通過呼叫stopservice 方法才能終止。一旦用stopse...