Want to become a better, more effective Android developer? Get a new tip every Wednesday that can help you code smarter and create fast, reliable apps that look great.
- [Instructor] In a previous tip, I described how to use an intent service to manage a background task. And I showed how to quickly create an intent service using Android Studio and how to add code to start and manage the task. In this tip, I've cleaned up that code a bit so I'm only managing a single task. And in the handleActionFoo method, in the MyIntent service class, I'm logging messages using logcat output. Now I'm going to show you how to communicate back from the intent service to the user interface, which could be an activity or a fragment.
An intent service doesn't have a direction connection back to the user interface. So you have to send messages using a broadcast message. You could use the local broadcast manager class that's a part of the support library. And I've shown how to use that in a couple of courses. But in this tip, I'm going to describe how to use a third party open source product called EventBus. This library can help you manage broadcast messages that you can send from anywhere to anywhere in your application, with just a few lines of code.
EventBus works with a publisher subscriber/pattern. It lets you create and send a message from anywhere and receive and act on a message from anywhere. So you can send messages from a service to a fragment or to an activity, or anywhere else. The first step in using EventBus is to add it to your application. And you can do that through the project structure dialog. I've selected my app module, and I'll choose Dependencies. And then I'll click plus library dependency.
I'll type eventbus, one word, all lowercase. And click the Search button. And then I'll choose this option, org.greenroboteventbus. And I'm using version 3.0, but you should be able to use any more recent version if it appears. I'll continue on to add the library to my project. And that adds it to my Gradle Script under the app module right down here. And now EventBus is ready for use. In order to send a message with EventBus, you use plain old Java object classes or POJOCs, classes that have simple properties and getter methods.
Now I'm going to go to my base package. And I'll create a new sub package that I'll name Events. And then I'll add a new Java class and I'll call it MessageEvent. And it's a plain old Java object, so there's no superclass or interface. And I'll create it. Each message event can have as many different fields or properties as you want. I'm going to create just a single private field, it'll be a string and I'll name it message.
Now I'll use code generation. I'll select Code, Generate, and choose Constructor, and click OK. And that creates a constructor that receives that string and saves it to the field. And then critically I need a getter method, a method that will provide that value to anywhere else in the application. And once again I'll generate that. And I'll choose Getter. And click OK. And that's all I need in the plain old Java object.
There aren't any annotations or any other special code for event bus in the message event class. Next, I'll go to my service class. This method, handleActionFoo is handling the request and then executing some background task. And I added this code in the previous tip. I added a sleep call so I could simulate a longer running task. Right now, I'm outputting to the logcat console and I'm going to copy the string to the clipboard.
Now I'll create an instance for that message event class. I'll name it event and I'll instantiate it with new MessageEvent and I'll paste it in the string. And now I'm ready to send the event. I'll use the EventBus class, which should now be available in the list when you start typing it. It's a member of the package org.greenrobot.eventbus. From that class, I'll call a method called getDefault. And from there I'll call the post method and I'll pass in the event object.
And that's it. That's all you need to do to send a message from anywhere in the application Create the event object and post it. Now receiving the event takes a little bit more work. I'll go to my main activity class. And, first, I'm going to register this activity with EventBus. You can do that in the onCreate method. I'll go to the onCreate method toward the end. And I'll call EventBus.getDefault again.
And then register. And I'll pass in this as the object that's registering to listen for events. Whenever you register an object to listen for events, you also have to unregister it. So I'm going to implement the onDestroy lifecycle method. And I'll call EventBus.getDefault.unregister and pass in this. And now this activity can listen for as many events as you like. To listen for any particular event, create a public method that receives that event as its one and only argument and has a return type of void.
And in this method, I'm going to call log and that's my own internal method. And I'll pass in event.getMessage. So whatever string was passed from the service will now be displayed in my console. Finally, I need to add an annotation to this method. It's called subscribe. And it's a member of the greenrobot.EventBus package. When you call the subscribe annotation, by default, it's going to be working on the same thread as whatever is sending the message.
But that's going to work in this case. My service is running on one thread, my activity on another. So I'm going to add something called a thread mode argument. And I'll set it to a constant of ThreadMode.MAIN. And thread note is an enumeration that's a member of the EventBus library. Up at the top, I'll look at my imports. And you'll see that there are important statements for the Event Bus class, for the subscribe annotation, and for the ThreadMode enumeration. Now notice that onMessageEvent is dimmed out right now, and that's because it's showing that it's not being called from anywhere.
But I'll select Build and then Make Project. And that results in generating a bunch of code in the background. And I should now be able to run the application on my device. When click the Run Code button, I immediately see a message that the service has started. And each time I click, I see the message again. Now I'll go back to my intent service and I'll send another message. This time I'll send a message showing the parameters that we received after the sleep call.
I'll copy that string to the clipboard and I'll once again create the event object. I won't set the type this time, I'm just going to reuse that declaration. And I'll create a message event and pass in the string. Then I'll duplicate this line of code and move it down. And now I'm sending two events. I'll click the button and I'll see the first event and then after two seconds, I see the second one.
I click again and two seconds later the second one appears. I'll clear the log and click twice in succession. And I see starting and then the received values. Then I see starting immediately and two seconds later the received values again. So the key to using EventBus is that first you have to add it to the project. And then you have to create event classes that contain your messages. You then post the messages from the sender. And then the receiving object you register and unregister as needed.
And then set up custom methods to receive and act on the messages. EventBus does pretty much the same thing as Local Broadcast Manager, but it has a lot more options and takes a lot less code.
Skill Level Intermediate
Q: Why can't I earn a Certificate of Completion for this course?
A: We publish a new tutorial or tutorials for this course on a regular basis. We are unable to offer a Certificate of Completion because it is an ever-evolving course that is not designed to be completed. Check back often for new movies.