刘瑞良
刘瑞良

Reputation: 1

when activity starts service, data in activity cannot be delivered to service immediately

08-16 21:11:29.053 10913-10913/com.oyyx.servicetest D/EventBus: No subscribers registered for event class com.oyyx.servicetest.TestAction 08-16 21:11:29.053 10913-10913/com.oyyx.servicetest D/EventBus: No subscribers registered for event class org.greenrobot.eventbus.NoSubscriberEvent

look like eventbus find subscribe method earlier than creating service


    @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);
}

//start service and post data(Activity)

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

//try to receive data(service)

08-16 09:58:45.987 1507-1507/com.oyyx.servicetest E/MY SERVICE: onCreate executed 08-16 09:58:45.987 1507-1507/com.oyyx.servicetest E/MY SERVICE: onStartCommand executed

click start service button log first and data cannot be delivered.

08-16 10:02:25.297 1507-1507/com.oyyx.servicetest E/MY SERVICE: startService 08-16 10:02:25.297 1507-1507/com.oyyx.servicetest E/MY SERVICE: onStartCommand executed

click start service button twice and data come in.

Upvotes: 0

Views: 62

Answers (1)

cmoaciopm
cmoaciopm

Reputation: 2256

Are you using EventBus library? If yes, try to use sticky event.

@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);
}

Refer sticky events.

Upvotes: 0

Related Questions