Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android Threads and Services But Wait There's More! Foreground Services

How do I notify the MainActivity when the song completes?

When the song ends, the button on the UI still says "Pause". I'm trying to get it to change back to "Play" when the song ends.

In the setOnCompletionListener, both the service and foreground are stopped. I thought this would be the place cause the button to change to "Play".

I thought I would send a message from the service, but the service does not know about activity.

What would be the best approach to accomplish this?

1 Answer

Ben Deitch
Ben Deitch
Treehouse Teacher

Hey Jeff!

First create a Messenger that we can use to communicate with the ActivityHandler:

public Messenger mActivityMessenger;
public void onCompletion(MediaPlayer mp) {
    Message message = Message.obtain();
    message.arg1 = 3;
    try {
    } catch (Exception e) {}

Then set the new 'mActivityMessenger' field by using the 'replyTo' property of the Message we pass to our PlayerHandler:

public void handleMessage(Message msg) {
    if (msg.replyTo != null) {
        mPlayerService.mActivityMessenger = msg.replyTo;

And finally add another 'else' branch to handle our new message argument:

else if (msg.arg1 == 3) {

Hope that helps!