Android: background computation options - android

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

Related

Android : Run A task in a separate thread outside application scope

I am trying to do specific task in a separate thread in android using Thread Pool executor with the Max thread size of 5 making sure there can be five parallel task would be run at a time. But problem with this approach is When I close my application the thread will also be killed. I want this to run out of application scope.
I could have opted for service with the AIDL . But problem with this is I need to keep on bind and unbind to the service and I need to parcel the object before I need to send it. Also when the task is completed i need to communicate back to the calling application. This I could any how achieve using Broadcast. I was wondering If I can make a thread run in a separate process or I need to go with AIDL only ? Please help me understand!
A thread is, by definition, part of an application. Then, it's not possible to have a thread outside an app.
When you have an app that never creates nor uses new threads, you're running a main thread, that uses the full CPU time assigned by the OS to the app.
Since this, your options are:
1) To leave your app running in background and connect to it.
2) To use the service way.
Hope this help you to understand.
A service sounds like what you want (since it can keep running even if the application goes away). It's more of a pain with the AIDL stuff, but that's what you need to do to get the behaviour you're asking for.

Confused about MusicService

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.

Service vs Thread in Android

I am looking for what service should be used in android applicaton.
Docs says
A Service is an application component that can perform long-running operations in the background and does not provide a user interface.
I have read this thread Application threads vs Service threads that saying same services are for running operation in background.
But here this can be done using Thread also. Any difference between them and where you should use them
UPDATE based on latest documentation:
Android has included in its documentation on when you should use Service vs Thread. Here is what it says:
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.
Another notable difference between these two approaches is that Thread will sleep if your device sleeps. Whereas, Service can perform operation even if the device goes to sleep. Let's take for example playing music using both approaches.
Thread Approach: the music will only play if your app is active or screen display is on.
Service Approach: the music can still play even if you minimized your app or screen is off.
Note: Starting API Level 23, you should Test your app with Doze.
Android Documentation - Services
A Service is meant to run your task independently of the Activity, it allows you to run any task in background. This run on the main UI thread so when you want to perform any network or heavy load operation then you have to use the Thread there.
Example : Suppose you want to take backup of your instant messages daily in the background then here you would use the Service.
Threads is for run your task in its own thread instead of main UI thread. You would use when you want to do some heavy network operation like sending bytes to the server continuously, and it is associated with the Android components. When your component destroy who started this then you should have stop it also.
Example : You are using the Thread in the Activity for some purpose, it is good practice to stop it when your activity destroy.
This is the principle i largely follow
Use a Thread when
app is required to be visible when the operation occurs.
background operation is relatively short running (less than a minute or two)
the activity/screen/app is highly coupled with the background operation, the user usually 'waits' for this operation to finish before doing anything else in the app.
Using a thread in these cases leads to cleaner, more readable & maintainable code. That being said its possible to use a Service( or IntentService).
Use a Service when
app could be invisible when the operation occurs (Features like Foreground service could help with operations being interrupted)
User is not required to 'wait' for the operation to finish to do other things in the app.
app is visible and the operation is independent of the app/screen context.
Reference from https://developer.android.com/guide/components/services.html
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().
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.
My Approach for explanation is simple:
Create a thread when you are in the activity and want to do some background operation with frequent communication with the main thread.
Alert- Don't create too many threads as 1 thread is equal to 1 processor thread. If you want to do parallel processing with threads(multiple) try your hands on Executors
Now you want long running operations with less interaction with UI then go for Service. Keep in mind service runs on UI thread. But now you want the processing should be done in background thread, then go for Intent Service.Intent service maintains their Thread Pools and do not create new threads and runs your tasks serially.

Difference between Android application spawning thread vs. Service?

I have an Android application that has a need to perform work in the background and on a separate thread. For my first proof-of-concept I subclassed the Application class and inside onCreate() I spawn a Thread that does the background work. This works just great. However, I just realized that in the past I've used a service for situations like this.
The question is, is there a reason to do work on a Thread spawned from a Service instead of a Thread spawned by Application.onCreate()? The Service is supposed to perform "background" work (it uses the UI thread unless a Thread is used, I know) that is independent of the Activity and can run while no Activity is visible. Using an Application-based thread seems to accomplish all this just as well. By not using a Service it actually removes complexity because the Activity just accesses the Application singleton. As far as I know I have no need to bind to the Service.
Will I get bit by lifecycle corner cases that using a Service would prevent? That's the only concern I have over this approach, but otherwise I'm not sold on the benefits of a Service.
The difference would be if you want the thread to run in the background only when the Activity is running or if you want it to continue to run when the user leaves.
Services are capable of running in the background even when the Activity is no longer available. They are intended to be used when your app should continue to do work without any user involvement in the near future. If you run the Thread in the Service, the thread will continue to run even when the user leaves the app. This can be beneficial sometimes as the user may want you to keep downloading a really large file but doesn't want the app to continue to run in the foreground. Then, a few hours (days, months, years) later the user can re-enter the app to read the file.
If, however, you're using a thread that needs to constantly update the UI based on results, it may be more beneficial to launch it within the Activity since it has no real purpose to run in a Service. It also may be easier in your program for your Thread to talk to the UI if it's in the Activity rather than the Service. (There may be some performance benefits as Android doesn't have to handle yet another Service on it's list, but that's purely speculation on my part. I have no proof of it.)
NOTE: Threads created in Activities will still continue to run even when the Activity quits. However, this is merely because the app is still in memory. The Activity and it's thread are on a higher priority to be deleted from memory than a Service thread when the Activity is no longer within view.
If your application is not either in the foreground, or visible, then it's more likely to be killed off by the system. If you run your code as a service, rather than a thread spawned by a background process, then your task will survive for longer. No guarantees, so you still need to manage the process lifecycle properly, but running as a service is likely to give more reliable results.
See http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html

Android: AsyncTask vs Service

Why do I read in the answer to most questions here a lot about AsyncTask and Loaders but nothing about Services? Are Services just not known very well or are they deprecated or have some bad attributes or something? What are the differences?
(By the way, I know that there are other threads about it, but none really states clear differences that help a developer to easily decide if he is better off using the one or the other for an actual problem.)
In some cases it is possible to accomplish the same task with either an AsyncTask or a Service however usually one is better suited to a task than the other.
AsyncTasks are designed for once-off time-consuming tasks that cannot be run of the UI thread. A common example is fetching/processing data when a button is pressed.
Services are designed to be continually running in the background. In the example above of fetching data when a button is pressed, you could start a service, let it fetch the data, and then stop it, but this is inefficient. It is far faster to use an AsyncTask that will run once, return the data, and be done.
If you need to be continually doing something in the background, though, a Service is your best bet. Examples of this include playing music, continually checking for new data, etc.
Also, as Sherif already said, services do not necessarily run off of the UI thread.
For the most part, Services are for when you want to run code even when your application's Activity isn't open. AsyncTasks are designed to make executing code off of the UI thread incredibly simple.
Services are completely different: Services are not threads!
Your Activity binds to a service and the service contains some functions that when called, blocks the calling thread. Your service might be used to change temperature from Celsius to Degrees. Any activity that binds can get this service.
However AsyncTask is a Thread that does some work in the background and at the same time has the ability to report results back to the calling thread.
Just a thought: A service may have a AsyncTask object!
Service is one of the components of the Android framework, which does not require UI to execute, which mean even when the app is not actively used by the user, you can perform some operation with service. That doesn't mean service will run in a separate thread, but it runs in main thread and operation can be performed in a separate thread when needed.
Examples usages are playing music in background, syncing data with server in backgroud without user interaction etc
AsyncTask on other hand is used for UI blocking tasks to be performed on a separate thread. It is same like creating a new thread and doing the task when all the tasks of creating and maintaining the threads and send back result to main thread are taken care by the AsyncTask
Example usage are fetching data from server, CRUD operations on content resolver etc
Service and asynctasks are almost doing the same thing,almost.using service or a asynctask depends on what is your requirement is.
as a example if you want to load data to a listview from a server after hitting some button or changing screen you better go with a asynctask.it runs parallel with main ui thread (runs in background).for run asynctack activity or your app should on main UI thread.after exit from the app there is no asynctask.
But services are not like that, once you start a service it can run after you exit from the app, unless you are stop the service.like i said it depends on your requirement.if you want to keep checking data receiving or check network state continuously you better go with service.
happy coding.
In few cases, you can achieve same functionality using both. Unlike Async Task, service has it's own life cycle and inherits Context (Service is more robust than an Async Task). Service can run even if you have exited the app. If you want to do something even after app closing and also need the context variable, you will go for Service.
Example: If you want to play a music and you don't want to pause if user leaves the app, you will definitely go for Service.
Comparison of a local, in-process, base class Service✱ to an AsyncTask:
✱ (This answer does not address exported services, or any service that runs in a process different from that of the client, since the expected use cases differ substantially from those of an AsyncTask. Also, in the interest of brevity, the nature of certain specialized Service subclasses (e.g., IntentService, JobService) will be ignored here.)
Process Lifetime
A Service represents, to the OS, "an application's desire to perform a longer-running operation while not interacting with the user" [ref].
While you have a Service running, Android understands that you don't want your process to be killed. This is also true whenever you have an Activity onscreen, and it is especially true when you are running a foreground service. (When all your application components go away, Android thinks, "Oh, now is a good time to kill this app, so I can free up resources".)
Also, depending on the last return value from Service.onCreate(), Android can attempt to "revive" apps/services that were killed due to resource pressure [ref].
AsyncTasks don't do any of that. It doesn't matter how many background threads you have running, or how hard they are working: Android will not keep your app alive just because your app is using the CPU. It has to have some way of knowing that your app still has work to do; that's why Services are registered with the OS, and AsyncTasks aren't.
Multithreading
AsyncTasks are all about creating a background thread on which to do work, and then presenting the result of that work to the UI thread in a threadsafe manner.
Each new AsyncTask execution generally results in more concurrency (more threads), subject to the limitations of the AsyncTasks's thread-pool [ref].
Service methods, on the other hand, are always invoked on the UI thread [ref]. This applies to onCreate(), onStartCommand(), onDestroy(), onServiceConnected(), etc. So, in some sense, Services don't "run" in the background. Once they start up (onCreate()), they just kinda "sit" there -- until it's time to clean up, execute an onStartCommand(), etc.
In other words, adding additional Services does not result in more concurrency. Service methods are not a good place to do large amounts of work, because they run on the UI thread.
Of course, you can extend Service, add your own methods, and call them from any thread you want. But if you do that, the responsibility for thread safety lies with you -- not the framework.
If you want to add a background thread (or some other sort of worker) to your Service, you are free to do so. You could start a background thread/AsyncTask in Service.onCreate(), for example. But not all use cases require this. For example:
You may wish to keep a Service running so you can continue getting location updates in the "background" (meaning, without necessarily having any Activities onscreen).
Or, you may want to keep your app alive just so you can keep an "implicit" BroadcastReceiver registered on a long-term basis (after API 26, you can't always do this via the manifest, so you have to register at runtime instead [ref]).
Neither of these use cases require a great deal of CPU activity; they just require that the app not be killed.
As Workers
Services are not task-oriented. They are not set up to "perform a task" and "deliver a result", like AsyncTasks are. Services do not solve any thread-safety problems (notwithstanding the fact that all methods execute on a single thread). AsyncTasks, on the other hand, handle that complexity for you.
Note that AsyncTask is slated for deprecation. But that doesn't mean your should replace your AsyncTasks with Services! (If you have learned anything from this answer, that much should be clear.)
TL;DR
Services are mostly there to "exist". They are like an off-screen Activity, providing a reason for the app to stay alive, while other components take care of doing the "work". AsyncTasks do "work", but they will not, in and of themselves, keep a process alive.

Categories

Resources