2012-04-17 24 views
1

我正在使用Android服務,解釋如下here。我打電話doBindService()onCreate()並試圖撥打onResume()中的mBoundservice的方法之一。這是我遇到問題的地方。此時,mBoundService仍爲空,大概是因爲mConnection.onServiceConnected()尚未被調用。Android服務在onResume中的mBoundService null

有什麼方法可以調用mBoundService的方法onResume(),或者有沒有辦法解決這個問題?

回答

1

它沒有被明確在official dev guide是bindService()實際上是一個異步調用說:

客戶端可以通過調用bindService綁定到服務()。當它這樣做時,它必須提供ServiceConnection的實現,它監視與服務的連接。 bindService()方法立即返回沒有值,但是當Android系統創建客戶端和服務之間的連接時,它會調用ServiceConnection上的onServiceConnected()以提供客戶端可以用來與服務進行通信的IBinder。

有一個滯後(雖然瞬間,但仍然滯後)調用bindService()之後和之前的系統準備/實例化一個可用的服務實例(NOT NULL),並把它背在ServiceConnection.onServiceConnected()回調。 onCreate()和onResume()之間的時間間隔太短而無法克服延遲(如果活動是第一次打開的話)。

假設您想在onResume()中調用mBoundservice.foo(),常用的解決方法是在第一次創建活動時設置布爾狀態並在onResume()方法中調用onServiceConnected()回調把它當且僅當狀態設置,有條件的控制代碼執行,即調用mBoundservice.foo()的基礎上different Activity lifecycle

LocalService mBoundservice = null; 
boolean mBound = false; 

... ... 

private ServiceConnection mConnection = new ServiceConnection() { 
    @Override 
    public void onServiceConnected(ComponentName className, IBinder service) { 
    LocalBinder binder = (LocalBinder) service; 
    mBoundservice = binder.getService(); 
    mBound = true; 
    // when activity is first created: 
    mBoundservice.foo(); 
    } 

    ... ... 
}; 

... ... 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    // call bindService here: 
    doBindService(); 
} 

@Override 
protected void onResume() { 
    super.onResume(); 
    // when activity is resumed: 
    // mBound will not be ready if Activity is first created, in this case use onServiceConnected() callback perform service call. 
    if (mBound) // <- or simply check if (mBoundservice != null) 
    mBoundservice.foo(); 
} 

... ... 

希望這有助於。