2017-08-16 68 views
0

08-16 21:11:29.053 10913-10913/com.oyyx.servicetest D/EventBus:未註冊事件類的訂戶com.oyyx.servicetest .TestAction 08-16 21:11:29.053 10913-10913/com.oyyx.servicetest d/EventBus:沒有爲事件類註冊用戶org.greenrobot.eventbus.NoSubscriberEvent當活動開始服務時,活動中的數據不能立即傳遞到服務

樣子eventbus發現早於訂閱方法創建服務


@OnClick(R.id.start_service) 
public void startService() { 
    Intent intent = new Intent(this, MyService.class); 
    TestAction testAction = new TestAction(); 
    testAction.setString("startService"); 
    startService(intent); 
    BusProvider.getInstance().post(testAction); 
} 

//啓動服務和後數據(活動)

@Subscribe 
public void testAction(TestAction testAction) { 
    Log.e(TAG, testAction.getString()); 
} 

//嘗試接收數據(服務)

9月8日至16日:58:45.987 1507年至1507年/ com.oyyx。 servicetest E /我的服務:執行的onCreate 九月八日至16日:58:45.987 1507至1507年/ com.oyyx.servicetest E /我的服務:onStartCommand執行

點擊啓動服務按鈕登錄第一和數據不能交付。

10月8日至16日:02:25.297 1507年至1507年/ com.oyyx.servicetest E/MY SERVICE: startService 10月8日至16日:02:25.297 1507年至1507年/ com.oyyx.servicetestë /我的服務:onStartCommand執行

點擊啓動服務按鈕兩次和數據進來

+0

您可以將TestAction作爲Intent-arguments傳遞給您的服務,而不使用EventBus。 – Christopher

回答

0

是否使用EventBus庫?如果是,請嘗試使用粘性事件。

@OnClick(R.id.start_service) 
public void startService() { 
    Intent intent = new Intent(this, MyService.class); 
    TestAction testAction = new TestAction(); 
    testAction.setString("startService"); 
    BusProvider.getInstance().postSticky(testAction); 
    startService(intent); 
} 

參照sticky events

+0

真誠地感謝您的回覆,我發現eventbus會在創建服務之前找到訂閱方法。所以當數據要傳遞時,只需使用intent .... –