關於Activity綁定到Service上的作用和方法過程


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

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

private final IBinder binder = new MyBinder();

@Override
public IBinder onBind(Intent intent) {
    return binder;
}
public class MyBinder extends Binder {

    MyService getService(){
      return MyService.this;
    }
}        

 

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

// Reference to the service
private MyService serviceBinder;

// Handles the connection between the service and activity
private ServiceConnection mConnection = new ServiceConnection(){
  
  public void onServiceConnected(ComponentName className, IBinder service) {     // Called when the connection is made.     serviceBinder = ((MyService.MyBinder)service).getService();   }
  
public void onServiceDisconnected(ComponentName className) {     // Received when the service unexpectedly disconnects.     serviceBinder = null;   }
};

 

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

@Override
public void onCreate(Bundle icicle) {
  super.onCreate(icicle);
  
// Bind to the service   Intent bindIntent = new Intent(MyActivity.this, MyService.class);   bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE); }

 

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

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

 

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


免責聲明!

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



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