This is very basic question but I am unable to figure it out because as I read that Service runs on main thread. So why do we need to create a Service? and because for intense CPU task we need to create Async task or thread in Service then why don't we create them in activity or application class?
I wanted to create a service which will continuously perform a set of task when it is started. I can't find any method in Service which will run in loop. Is there is such method? or do I have to create a thread in service to set a loop?
why don't we create them in activity or application class?
You can, but it depends of task you want to accomplish. The main characteristic of a Service is that it runs in background, decoupled from Activity life cycle.
Imagine the following situation, you are working on a Media Player application and would like to let the users play music, even when they exit the application, in background.
Now, if you put the media player logic in Activity, then when users will leave the app, the music will stop, as this will terminate the media player. That is not good, we want the music to continue playing in background when they leave the app. Well, in order to achieve this, you should put the playing logic in a Service.
Also, take a look over IntentService class, which provides its own worker thread, so you shouldn't define your own.
I can't find any method in Service which will run in loop. Is there
is such method?
No, there isn't. You either start the service again, or, create a loop inside the service.
Related
I want to achieve following goals:
Record Audio
Send Audio to Server
Play Audio
I know that First 2 tasks are possible by Using Service as I've done that in one of the previous apps but when it comes to playing an audio file, it needs to be triggered from an Activity.
Because accessing Activity from Service can be achieved by using BroadcastReceiver but what about accessing method of a Service from an Activity?
So, now comes the question: Whether to go for Service itself for Playing the audio also(triggered from activity) OR to use IntentService.
Documentation says,
No easy or direct way to interact with user interface directly from IntentService.
and
Any tasks started using IntentService cannot be interrupted
I may want to stop recording ant time and play it any time.
Which would suit t he requirement best --> Service OR IntentService ??
Any suggestions will be highly appreciated.
I would use a Service rather than an IntentService for what you need.
In particular, use a bound Service which allows two-way communication between the Activity which binds to it and from the Service to the Activity.
The IntentService class is designed for one-shot operations using its own worker thread, once the work on the thread is complete, the thread terminates and the IntentService calls stopSelf() to terminate itself. This means any user interaction between the user (via an Activity) and an IntentService is problematic.
A bound Service on the other hand will exist until it is either explicitly stopped or untill the last bound component unbinds. This allows for longer term interaction.
For playback, the fact a Service runs on the UI thread isn't an issue if you use something like MediaPlayerwhich handles its own thread for playback purposes.
Further to this, if you use a bound Service, MediaPlayer and MediaController, you can control play, stop, pause, seek etc from the Activity.
EDIT: For further information see... Bound Services
I've built a music player which is running on a Service.
I'm preforming various actions as play, pause, next song, previous song etc through a binding to the service from my activity.
It works totally fine.
So to my question:
Is it ideal to put the service on a new thread? I know Service run by default on Main/UI thread.
If not, how do I know when to actually put something on a new thread? Can I put the whole Service instance on new thread or just a part of the code in the Service?
I guess this is called a long running service, shouldnt that be on a own thread to not block the UI?
When debugging I can see this in Logcat: I/Choreographer(691): Skipped 60 frames! The application may be doing too much work on its main thread...
That got me wondering too! :o
As my title says, I'm very confused about this!
You are right, Services are not threads (they do not create a different thread).
When started form an activity they would block the main/UI thread fi running long operations.
you can use IntentService - which start their own thread to perform background long running operations - but that would probably suits a download file task or long running calculation better than playing music.
note that IntentService creates and destroys the thread by itself (when the work is done).
Another option would be to create you own thread manually.
That said, I would consider this article:
http://developer.android.com/guide/topics/media/mediaplayer.html
It talks about a service in the foreground using startForeground() which adds a notification to the status bar, letting the user be aware of the fact that the service is running - as well as promoting the service so it won't get destroyed in case of low memory conditions (it could be - but it will probably be the last one to be closed).
the example is about running media player while taking the main thread blocking into consideration as well as handling system events to pause and play music as expected (using BroadcastReceiver )
Also note this:
http://developer.android.com/guide/components/services.html
Should you use a service or a thread?
A service is simply a component that can run in the background even
when the user is not interacting with your application. Thus, you
should create a service only if that is what you need.
If you need to perform work outside your main thread, but only while
the user is interacting with your application, then you should
probably instead create a new thread and not a service. For example,
if you want to play some music, but only while your activity is
running, you might create a thread in onCreate(), start running it in
onStart(), then stop it in onStop(). Also consider using AsyncTask or
HandlerThread, instead of the traditional Thread class. See the
Processes and Threading document for more information about threads.
Remember that if you do use a service, it still runs in your
application's main thread by default, so you should still create a new
thread within the service if it performs intensive or blocking
operations.
I know that a process is an executing instance of an a program running in the foreground or background and that background processes run asynchronously(runs outside the main thread).
Would background music in your application be an example of a background process?(doesn't freeze up your UI in the main thread and it runs in its own thread)
Does process imply then that another program is running the music in the background?
I don't think that you need another process for playing music - you just need another thread. I don't think that you want to play music while your app is not in the foreground. For example if your app is a game which only produces sounds when it is active.
Obviously this is not true if your app is a media player which still plays music while in the background letting user interact with it using notifications which let the user play/pause, skip a song or stop playback.
Please see a question like this one: How to put media controller button on notification bar?
Your android application consist of process, services, threads, message queues. It application developer choice when to use what. As good developer, you should always try to make you application user experience smooth without and any hang. Always perform heavy/time consuming activity with service or async threads, and avoid such activity on main thread as it cause UI hangs.
I am new to Android application development. My first project is to create a tuner, which requires to record audio and analyse it in real time.
I have read a lot on background operations in Android, but I am having trouble deciding what to use:
Asynctask : Android documentation says it should be kept for short computations, but I need to analyse data for more than a few seconds.
Intentservice : Better suited for long computations, but it can't be stopped whenever I want with a button.
Worker thread : The limitations seem to be similar to that of Asynctask.
On the following link is an example I found that is similar to what I want to do. Can a worker thread still be a good choice for long computations ? Is it thread safe to use a while loop with a flag to stop the computation ?
http://developer.samsung.com/android/technical-docs/Displaying-Sound-Volume-in-Real-Time-While-Recording
Edit: I have successfully created a bound service. Inside this service, a new thread is created to update a value in a loop, which is then broadcast. But when I unbind from the service, the thread continues to run. The value will still be updated even if I close the app and restart it.
So I am back to my initial problem. How is such a thread stopped ?
Edit: Problem solved with a simple flag activated in onUnbind() that stops the loop inside the thread.
You actually want a Service, but not an IntentService. You want a Service that will run in the background and which can be controlled through Activity (and will keep working after Activity is closed). This is a common architecture for such tasks. Here is an example of open source music player for Android:
https://github.com/kreed/vanilla/blob/master/src/org/kreed/vanilla/PlaybackService.java
I've created an application which does synchronization with the server.
I've already have a code, which does synchronization once user pressed a button. Now it is time to add Service there.
I have the following questions with regards to the services on android:
will the service be started if user never run application before? (i.e. just installed that)
when the service will be started first time? can I start it from onCreate of the main application?
if user presses Synchronize button in the application, should I start that Service or should I have different process for the same? How can I check then that background synchronization is not happening at the same time?
should I use ASyncTask, even if the service is started as
startService(new Intent(this, ServiceSync.class));
The preferred approach to syncing data in Android is providing a SyncAdapter to perform the sync. You have a very nice summary of the required steps in this post.
You will also find these articles useful.
Edit:
1-2-3: You can use a bound service to manage the interaction and service methods from your activity. You have full working samples in the link provided. Basically, you bind to the service in your activity's onStart method and unbind onStop.
Remember that a service runs on the UI thread, so every time-consuming task such as fetching data over the network must be done in a separate thread.
4: You don't need an AsyncTask here.