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 Introducing Services Services Are Not Threads

Adit Doshi
Adit Doshi
2,142 Points

Service ques

Everytime we download a song we called service OnCreate method.. Which provides a new thread for each song .. It is sensible to make a new thread each time when we call service

Abubakar Abdulrahman
Abubakar Abdulrahman
3,284 Points

please can you elaborate more on this question.

2 Answers

Boban Talevski
Boban Talevski
24,793 Points

Additional explanation of the question is welcome, but anyway, for anyone wondering, we are not creating a new thread for every song. Because we are not calling the service's onCreate() method, in fact this is the comment I got generated when overriding the method in AS 3

     * Called by the system when the service is first created.  Do not call this method directly.

So it's called (only once?) by the system when the service is created, we shouldn't call it directly, otherwise "bad things will happen" I guess :). And if you check using Android Device Monitor, there's only one DownloadThread regardless of how many times the download button is clicked. And it's there even before the button is clicked, so the service's onCreate method was already called when the application started and it created the DownloadThread.

The startService method in the for each loop in the onClickListener in MainActivity just sends messages to the handler, but still one message(song) at a time, and they are queued so each song takes its time for "downloading" in that single Download thread. Every subsequent click just sends the same songs again and adds them to the queue, but they still get to be "downloaded" one at a time. Also, the call to startService seems to be triggering the service's onStartCommand method rather than onCreate.

And even if we kill the app process after clicking the download button multiple times, whatever messages(songs) we sent still get to be "downloaded" by the service when it's restarted.

Naor Malca
Naor Malca
3,841 Points

From here Service | Android Developer

onCreate() The system invokes this method to perform one-time setup procedures when the service is initially created (before it >calls either onStartCommand() or onBind()). If the service is already running, this method is not called.

That`s mean onCreate called ONE-TIME and in our case, the thread created only on time.