標籤:art blog details 伺服器端 value state top connected stat
前言
- Service作為Android四大組件之一,應用非常廣泛
- 本文將介紹Service其中一種常見用法:遠程Service
如果你對Service還未瞭解,建議先閱讀我寫的另外一篇文章:
Android四大組件:Service史上最全面解析
目錄
1. 遠程服務與本地服務的區別
- 遠程服務與本地服務最大的區別是:遠程Service與調用者不在同一個進程裡(即遠程Service是運行在另外一個進程);而本地服務則是與調用者運行在同一個進程裡
- 二者區別的詳細區別如:
2. 使用情境
多個應用程式共用同一個後台服務(遠程服務)
即一個遠程Service與多個應用程式的組件(四大組件)進行跨進程通訊
3. 具體使用
-
為了讓遠程Service與多個應用程式的組件(四大組件)進行跨進程通訊(IPC),需要使用AIDL
- IPC:Inter-Process Communication,即跨進程通訊
- AIDL:Android Interface Definition Language,即Android介面定義語言;用於讓某個Service與多個應用程式組件之間進行跨進程通訊,從而可以實現多個應用程式共用同一個Service的功能。
-
在多進程通訊中,存在兩個進程角色(以最簡單的為例):伺服器端和用戶端
-
以下是兩個進程角色的具體使用步驟:
伺服器端(Service)
步驟1:建立定義AIDL檔案,並聲明該服務需要向用戶端提供的介面
步驟2:在Service子類中實現AIDL中定義的介面方法,並定義生命週期的方法(onCreat、onBind()、blabla)
步驟3:在AndroidMainfest.xml中註冊服務 & 聲明為遠程服務
用戶端(Client)
步驟1:拷貝服務端的AIDL檔案到目錄下
步驟2:使用Stub.asInterface介面擷取伺服器的Binder,根據需要調用服務提供的介面方法
步驟3:通過Intent指定服務端的服務名稱和所在包,綁定遠程Service
接下來,我將用一個具體執行個體來介紹遠程Service的使用
4. 具體執行個體
- 執行個體描述:用戶端遠程調用伺服器端的遠程Service
- 具體使用:
4.1 伺服器端(Service)
建立一個伺服器端的工程:Service - server
先下Demo再看,效果會更好:Github_RemoteService_Server
步驟1. 建立一個AIDL檔案
步驟2. 在建立AIDL檔案裡定義Service需要與Activity進行通訊的內容(方法),並進行編譯(Make Project)
// 在建立的AIDL_Service1.aidl裡聲明需要與Activity進行通訊的方法package scut.carson_ho.demo_service;interface AIDL_Service1 { void AIDL_Service();}//AIDL中支援以下的資料類型//1. 基礎資料型別 (Elementary Data Type)//2. String 和CharSequence//3. List 和 Map ,List和Map 對象的元素必須是AIDL支援的資料類型;//4. AIDL自動產生的介面(需要匯入-import)//5. 實現android.os.Parcelable 介面的類(需要匯入-import)
步驟3:在Service子類中實現AIDL中定義的介面方法,並定義生命週期的方法(onCreat、onBind()、blabla)
MyService.java
public class MyService extends Service { // 執行個體化AIDL的Stub類(Binder的子類) AIDL_Service1.Stub mBinder = new AIDL_Service1.Stub() { //重寫介面裡定義的方法 @Override public void AIDL_Service() throws RemoteException { System.out.println("用戶端通過AIDL與遠程後台成功通訊"); } };//重寫與Service生命週期的相關方法 @Override public void onCreate() { super.onCreate(); System.out.println("執行了onCreat()"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { System.out.println("執行了onStartCommand()"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); System.out.println("執行了onDestory()"); } @Nullable @Override public IBinder onBind(Intent intent) { System.out.println("執行了onBind()"); //在onBind()返回繼承自Binder的Stub類型的Binder,非常重要 return mBinder; } @Override public boolean onUnbind(Intent intent) { System.out.println("執行了onUnbind()"); return super.onUnbind(intent); }}
步驟4:在AndroidMainfest.xml中註冊服務 & 聲明為遠程服務
<service android:name=".MyService" android:process=":remote" //將本地服務設定成遠程服務 android:exported="true" //設定可被其他進程調用 > //該Service可以響應帶有scut.carson_ho.service_server.AIDL_Service1這個action的Intent。 //此處Intent的action必須寫成“伺服器端包名.aidl檔案名稱” <intent-filter> <action android:name="scut.carson_ho.service_server.AIDL_Service1"/> </intent-filter> </service>
至此,伺服器端(遠程Service)已經完成了。
4.2 用戶端(Client)
建立一個用戶端的工程:Service - Client
先下Demo再看,效果會更好:Github_RemoteService_Client
步驟1:將服務端的AIDL檔案所在的包複製到用戶端目錄下(Project/app/src/main),並進行編譯
註:記得要原封不動地複製!!什麼都不要改!
步驟2:在主布局檔案定義“綁定服務”的按鈕
MainActivity.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="scut.carson_ho.service_client.MainActivity"> <Button android:layout_centerInParent="true" android:id="@+id/bind_service" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="綁定服務" /></RelativeLayout>
步驟3:在MainActivity.java裡
- 使用Stub.asInterface介面擷取伺服器的Binder;
- 通過Intent指定服務端的服務名稱和所在包,進行Service綁定;
- 根據需要調用服務提供的介面方法。
MainActivity.java
public class MainActivity extends AppCompatActivity { private Button bindService; //定義aidl介面變數 private AIDL_Service1 mAIDL_Service; //建立ServiceConnection的匿名類 private ServiceConnection connection = new ServiceConnection() { //重寫onServiceConnected()方法和onServiceDisconnected()方法 //在Activity與Service建立關聯和解除關聯的時候調用 @Override public void onServiceDisconnected(ComponentName name) { } //在Activity與Service建立關聯時調用 @Override public void onServiceConnected(ComponentName name, IBinder service) { //使用AIDLService1.Stub.asInterface()方法擷取伺服器端返回的IBinder對象 //將IBinder對象傳換成了mAIDL_Service介面對象 mAIDL_Service = AIDL_Service1.Stub.asInterface(service); try { //通過該對象調用在MyAIDLService.aidl檔案中定義的介面方法,從而實現跨進程通訊 mAIDL_Service.AIDL_Service(); } catch (RemoteException e) { e.printStackTrace(); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bindService = (Button) findViewById(R.id.bind_service); //設定綁定服務的按鈕 bindService.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //通過Intent指定服務端的服務名稱和所在包,與遠程Service進行綁定 //參數與伺服器端的action要一致,即"伺服器包名.aidl介面檔案名稱" Intent intent = new Intent("scut.carson_ho.service_server.AIDL_Service1"); //Android5.0後無法只通過隱式Intent綁定遠程Service //需要通過setPackage()方法指定包名 intent.setPackage("scut.carson_ho.service_server"); //綁定服務,傳入intent和ServiceConnection對象 bindService(intent, connection, Context.BIND_AUTO_CREATE); } }); } }
4.3 測試結果
從上面測試結果可以看出:
- 列印的語句分別運行在不同進程(看語句前面的包名);
- 用戶端調用了服務端Service的方法
即用戶端和服務端進行了跨進程通訊
4.4 Demo地址
- 用戶端:Github_RemoteService_Client
- 服務端:Github_RemoteService_Server
5. 總結
請點贊!因為你們的贊同/鼓勵是我寫作的最大動力!
相關文章閱讀
Android開發:最全面、最易懂的Android螢幕適配解決方案
Android開發:Handler非同步通訊機制全面解析(包含Looper、Message Queue)
Android開發:頂部Tab導覽列實現(TabLayout+ViewPager+Fragment)
Android開發:底部Tab功能表列實現(FragmentTabHost+ViewPager)
Android開發:JSON簡介及最全面解析方法!
Android開發:XML簡介及DOM、SAX、PULL解析對比
歡迎關注Carson_Ho的簡書!
不定期分享關於安卓開發的乾貨,追求短、平、快,但卻不缺深度。
Android:遠程服務Service(含AIDL & IPC講解)