Android Service學習總結(下)

2021-07-10 20:27:45 字數 2040 閱讀 3080

關於郭神service的講解的學習總結,想看郭神原版請看該鏈結

遠端service

遠端service,它現在執行在與主線程不同的執行緒當中,所以我們不能在serviceconnected方法裡面對它的public方法進行呼叫,只能是通過aidl來進行通訊,與此同時遠端service還可以實現程序間的通訊。

mainfest.xml檔案例項**如下:

myaidlservice的例項**如下:

inte***ce myaidlservice
步驟三:在myservice裡面實現aidl的介面,具體的做法如下:

/**

* 用來建立 service 和 activity之間的聯絡

*/@nullable

@override

public ibinder onbind(intent intent)

myaidlservice.stub binder = new myaidlservice.stub()

@override

public string touppercase(string str) throws remoteexception

return null;}};

在ibinder方法裡返回的就是實現介面的binder,這樣在繫結的activit裡面,無論是同乙個程序還是不同的程序,都可以呼叫這兩個public方法。

步驟四:在(同一程序下的)mainactivity當中對service進行繫結,首先就是serviceconnnection裡面的onserviceconnected的方法不同了,它要通過我們定義好的aidl介面去進行方法的呼叫,**如下:

注意:一定要整個資料夾都貼上過來

步驟六:接下來我們就可以呼叫我們的service裡面的方法啦,像步驟四一樣在(不同程序下的)secondactivity中生成serviceconnect的物件connection。**如下:

private serviceconnection connection = new serviceconnection()  catch (remoteexception e) 

}@override

public void onservicedisconnected(componentname name)

};

與步驟四沒有任何的區別,接下來就是重點要區分的。

步驟七:如何將service和activity聯絡在一起?這裡需要注意的是,在不同程序中,我們只能通過action的name來進行意圖的指定在android 5.0版本之前,我們可以直接用這種方式:

bindservice(intent, connection, bind_auto_create);

但是在實踐的過程中,我發現用5.0的系統的手機去啟動該應用會出現如下的錯誤:

經過查資料得知,在android 5.0版本之後不支援service的隱式意圖啟動,並給出了如下解決方案:

intent intent = new intent();

bindservice(intent, connection, bind_auto_create);

這樣我們就實現了service的程序間通訊,執行結果如下:

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 啟動服務

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