2013-08-17 126 views
1

我正在實施Service,它建立與服務器的TCP連接,然後允許客戶端通過此連接傳遞消息。客戶通過撥打電話bindService連接到服務。因此onServiceConnected在客戶端調用ServiceConnection對象。問題是onServiceConnectedbindService返回後立即調用,但此時我的Service未與服務器建立連接。連接未建立時,我能以某種方式延遲onServiceConnected呼叫嗎?如果這是不可能的,請爲我的情況建議一些好的模式。謝謝。如何延遲服務連接呼叫

+0

有兩個連接。一個應用程序<->服務,它可以並應該立即連接。另外,服務應該連接到服務器。應該有兩個連接。 –

回答

1

如下你應該這樣做:

服務代碼:

class MyService implements Service { 
    private boolean mIsConnectionEstablished = false; 

    // Binder given to clients 
    private final IBinder mBinder = new LocalBinder(); 

    public class LocalBinder extends Binder { 
     public MyService getService() { 
      // Return this instance of LocalService so clients can call public 
      // methods 
      return MyService.this; 
     } 
    } 

    public interface OnConnectionEstablishedListener { 
     public void onConnectionEstablished(); 
    } 

    private OnConnectionEstablishedListener mListener; 

    @Override 
    public void onCreate() { 
     super.onCreate(); 

     new Thread(new Runnable() { 
      @Override 
      void run() { 
       //Connect to the server here 

       notifyConnectionEstablished(); 
      } 
     }).start(); 
    } 

    @Override 
    public IBinder onBind(Intent intent) { 
     return mBinder; 
    } 

    private void notifyConnectionEstablished() { 
     mIsConnectionEstablished = true; 

     if(mListener != null) { 
      mListener.onConnectionEstablished(); 
     } 
    } 


    public void setOnConnectionEstablishedListener(
     OnConnectionEstablishedListener listener) { 

     mListener = listener 

     // Already connected to server. Notify immediately. 
     if(mIsConnectionEstablished) { 
      mListener.onConnectionEstablished(); 
     } 
    } 
} 

活動代碼:

class MyActivity extends Activity implements ServiceConnection, 
    OnConnectionEstablishedListener { 

    private MyService mService; 
    private boolean mBound; 

    @Override 
    public void onCreate() { 
     super.onCreate(); 

     //bind the service here 
     Intent intent = new Intent(this, MyService.class); 
     bindService(intent, this, BIND_AUTO_CREATE); 
    } 

    @Override 
    public void onServiceConnected(ComponentName className, IBinder service) { 
     LocalBinder binder = (LocalBinder) service; 
     mService = binder.getService(); 
     mBound = true; 

     mService.setOnConnectionEstablishedListener(this); 
    } 

    @Override 
    public void onServiceDisconnected(ComponentName arg0) { 
     mBound = false; 
    } 

    @Override 
    public void onConnectionEstablished() { 
     // At this point the service has been bound and connected to the server 
     // Do stuff here 
     // Note: This method is called from a non-UI thread. 
    } 
}