调用startService()方法发送otto事件后如何知道服务何时启动?

我有AlarmReceiver( BrodcastReceiver )启动DownloadService( Service )后,检查服务是否运行状态

 context.startDownloadServiceIfNotRunning()// kotlin extension function check service state 

在这一行之后,我正在发送otto事件到以前启动的服务

 BusStation.getBus().post(DownloadEvent()) // Actually this line fired before start of service 

但是即使是注册了事件,下载服务也没有收到这个事件。

在调试之后,我发现Otto事件在服务实际启动之前正在触发,因此它没有收到任何事件

所以有没有什么办法知道什么时候android服务正常启动,以接收otto事件

您可以将参数添加到意图。 如何使用参数,而不是奥托?

 Intent serviceIntent = new Intent(this,DownloadService.class); serviceIntent.putExtra("Key", "Value"); startService(serviceIntent); 

在开始服务的时候,你可以使用参数。

 @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); Bundle extras = intent.getExtras(); if(extras == null) { // Do something } else { String value = (String) extras.get("Key"); if (value.equals("Value")) { // Do same thing you want to do with Otto event. } } } 

编辑:如果你的事件不是一个时间关键的事件,你可以简单地延迟你的事件。

 new Handler().postDelayed(new Runnable() { @Override public void run() { BusStation.getBus().post(DownloadEvent()); } },1000); 

否则,你需要建立你自己的消息队列。