Android Activity綁定到Service


當一個Activity綁定到一個Service上時,它負責維護Service實例的引用,允許你對正在運行的Service進行一些方法調用。

       Activity能進行綁定得益於Service的接口。為了支持Service的綁定,實現onBind方法如下所示:

java代碼:

  1. private final IBinder binder = new MyBinder();
  2. @Override
  3. public IBinder onBind(Intent intent) {
  4. return binder;
  5. }
  6. public class MyBinder extends Binder {
  7. MyService getService()
  8. {
  9. return MyService.this;
  10. }
復制代碼


        ServiceActivity的連接可以用ServiceConnection來實現。你需要實現一個新的ServiceConnection,重寫onServiceConnected和onServiceDisconnected方法,一旦連接建立,你就能得到Service實例的引用。

java代碼:

  1. // Reference to the service
  2. private MyService serviceBinder;
  3. // Handles the connection between the service and activity
  4. private ServiceConnection mConnection = new ServiceConnection()
  5. {
  6. public void onServiceConnected(ComponentName className, IBinder service) {
  7. // Called when the connection is made.
  8. serviceBinder = ((MyService.MyBinder)service).getService();
  9. }
  10. public void onServiceDisconnected(ComponentName className) {
  11. // Received when the service unexpectedly disconnects.
  12. serviceBinder = null;
  13. }
  14. }; 
復制代碼


        執行綁定,調用bindService方法,傳入一個選擇了要綁定的Service的Intent(顯式或隱式)和一個你實現了的ServiceConnection實例,如下的框架代碼所示:

java代碼:

  1. @Override
  2. public void onCreate(Bundle icicle) {
  3. super.onCreate(icicle);
  4. // Bind to the service
  5. Intent bindIntent = new Intent(MyActivity.this, MyService.class);
  6. bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);
復制代碼


        一旦Service對象找到,通過onServiceConnected處理函數中獲得serviceBinder對象就能得到它的公共方法和屬性。

       Android應用程序一般不共享內存,但在有些時候,你的應用程序可能想要與其它的應用程序中運行的Service交互。

       你可以使用廣播Intent或者通過用於啟動Service的Intent中的Bundle來達到與運行在其它進程中的Service交互的目的。如果你需要更加緊密的連接的話,你可以使用AIDL讓Service跨越程序邊界來實現綁定。AIDL定義了系統級別的Service的接口,來允許Android跨越進程邊界傳遞對象。

 

sourceurl:http://www.eoeandroid.com/forum.php?mod=viewthread&tid=98881


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM