Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Threads and Services But Wait There's More! Messengers and Handlers: Activity

Need help understanding service

So I went through all the code for the lecture and the lectures themselves but I haven't understood how the PlayerHandler gets the different values of 0,1,2 for Message.arg1 if from the main acitvity we only ever pass 2 for arg1 . I tried debugging the code but still couldn't identify it. How does the Player Handler get different args from msg if ever only passed 2 to it.Is the ActivityHandler responsible,if yes then how ? it only ever replies with the same arg1 it got. so how does passing only 2 on button press pause or play the music. I tried debuging and noticed that the PlayerHandler onHandleMessage gets called twice once with 2 and again with button press args. so where does the second call come from. I went through the course again and even checked the code from site still no clarification. Also if in each onHandleMessage the replyTo is called then won't the acitivity and service keep constantly passing messages to each other. Please explain Ben Deitch .

3 Answers

Ben Deitch
STAFF
Ben Deitch
Treehouse Teacher

You're correct that the ActivityHandler is responsible. What happens is:

  • We click the Button which sends a Message to our PlayerHandler with arg1 = 2.
  • This puts us in 'case 2:' where we create a new Message and give it an arg1 of 0 or 1 (depending on if music is playing or not).
  • Then we send this new Message to the ActivityHandler, which updates the Button text. And, if the music state needs to be changed, it sends another different new Message (with arg1 of 0 or 1) back to PlayerHander which then plays or pauses the music.

Thank you for that. The main thing I was confused with was the logic of 0 and 1 and how the passing of them between the service and activity turned the music on and off, but now it's clear. Also , by our current code, aren't we constantly sending messages between Activity and Service ? Will it not be a load on device resources to keep constantly sending messages ? Is it possible to prevent this constant messaging and are the resources saved worth it ?

Ben Deitch
Ben Deitch
Treehouse Teacher

Nope. It stops once it gets back to the PlayerHandler with an arg1 of 0 or 1.

Okay

I'm still don't understand how this works.