[分享] Android Bound Service(一)

看板AndroidDev作者 (念不停 煩不煩?)時間9年前 (2014/11/24 22:52), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串1/1
這其實是小弟在復習 Service的時候順便做的筆記,希望各位大大能不吝指教~ 網頁版連結:http://blog.csdn.net/shanwu1985/article/details/41439521 ref:http://developer.android.com/guide/components/bound-services.html? Bound Service 「Bound Service是 Client-Server Interface 中的服務端,一個 Activity 可以透過 Bound Service 綁定一個服務,收發訊息,甚至進行進程間通訊。」Service類是一個 Abstract Class,而 Bound Service實現了 Service類,並實現了 onBind()方法,Activity 才能和 Service進行溝通。 所以,我們先從簡單的例子--讓一個 Activity 綁定一個 Service,讓 Service 能夠為 Activity 提供服務,同時,我已將練習的相關代碼提交至 GitHub上(https://github.com/shanwu/InterProcessCommPractice),有不同的分枝分別代表不同的例子,這樣可以使用 Github上的分枝比較功能()比較不同方法間的差異。 master 分枝:進程內通訊,代表的是官網 Extending the Binder class的例子。 ipc_messanger_example:跨進程通訊,代表的是官網 Using a Messenger的例子            (抱歉 branch 名英文拼錯 Orz) ipc_messenger_example_bidirection:同上,但是其為 Service, Activity 雙向                 互傳的例子。 ipc_aidl_example:跨進程通訊,簡單的 aidl 使用例子。 Extending Binder Service 客戶端的 Activity 可以透過呼叫 bindService()方法和服務端的 Service建立連結, 連結建立的時候,會先調用 Bound Service的 onBind() 方法,再來調用 onServiceConnected(),而如果是需要移除連結的話,便調用 unbindService()方法, 此時Bound Service會直接調用 onDestory(),然後服務結束。 在Bound Service寫一個繼承 Binder的類-LocalBinder,主要是在進程內通訊時, 在 onBind()的時候,能夠用方法來返回 Bound Service的對象: [java] view plaincopy public class LocalBinder extends Binder { public Service getService() { return WorkerService.this; } } 宣告一個 LocalBinder的私有全局變量 [java] view plaincopy public class WorkerService extends Service { private final IBinder mBinder = new LocalBinder(); 同時覆寫 onBind()方法 [java] view plaincopy @Override public IBinder onBind(Intent intent) { Log.d("guang","onBind"); return mBinder; } 而在Activity端,我們需要使用 bindService()來進行綁定 Bound Service的工作 [java] view plaincopy @Override public void onClick(View v) { final int id = v.getId(); switch (id) { case R.id.btn_start: Intent intent = new Intent(MainActivity.this, WorkerService.class); bindService(intent, mServiceConn, Context.BIND_AUTO_CREATE); break; 同時我們需要將接口 ServiceConnection的方法覆寫,在連結開始的時候, iBinder便是onBind所返回的 IBinder類變量,所以我們將它強轉為LocalBinder, 然後調用LocalBinder裏的方法以取得 Bound Service 的對象,將它存於全局 變量中,之後便可以調用他的方法。這邊要註意的是 onServiceDisconnected 一般情況下不會調用,只有在 Service發生異常導致連結結束才會調用。 [java] view plaincopy mServiceConn = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { WorkerService.LocalBinder lBinder = (WorkerService.LocalBinder) iBinder; mService = (WorkerService) lBinder.getService(); Log.d("guang","onServiceConnected"); mIsBind = true; } @Override public void onServiceDisconnected(ComponentName componentName) { Log.d("guang","onServiceDisconnected"); mIsBind = false; } }; 調用它的方法 [java] view plaincopy case R.id.btn_sing: if (mIsBind) { mService.makeSingingService(); } break; 全部代碼均可自 GitHub取得~ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 222.128.142.203 ※ 文章網址: http://www.ptt.cc/bbs/AndroidDev/M.1416840779.A.AFB.html
文章代碼(AID): #1KSqPBhx (AndroidDev)