当活动开始服务时,活动中的数据无法立即传递给服务

时间:2017-08-16 02:08:24

标签: android service event-bus

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 find subscribe方法

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

//尝试接收数据(服务)

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

点击开始服务按钮日志首先,无法投放数据。

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已执行

点击开始服务按钮两次,数据进入。

1 个答案:

答案 0 :(得分: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