should I use setDaemon() in android? - android

I'm creating a service Thread for my application, this thread will perform background tasks, and therefore it'll be usage only if my Main thread is running.
So should I declare it as a Daemon ?

On Android, it's better to make sure you manage your threads explicitly. Tell them when to terminate.
See a related discussion here. They didn't find a solution, and observed long-living threads instead:
What hooks do we have in order to do worker thread termination on application exit
Note that standard Java shutdown hooks are not guaranteed on this platform:
http://developer.android.com/reference/java/lang/Runtime.html#addShutdownHook%28java.lang.Thread%29
So, instead of relying on an (undocumented?) belief that Android will properly kill your VM anyway and guessing on daemon/not daemon, it seems to be better to control the threads.

Not really. Android doesn't have a main() methods for apps and they don't exit, but are managed by the system. If it decides to kill your app to free resources, it (most probably) won't care if you have daemon threads or not.

Related

Under what conditions are background local services preferable to threads in Android?

By Local Service is I mean a Service that is only connected to by the host application. It may use the Binder-subclass version of Services or it may use Messenger -- it doesn't matter. Also, I'll consider only services that run on background threads although I think this applies regardless.
I have been trying to figure out the value of local services over a simple background thread. I've seen it written many times that the background thread version somehow ties you to the Activity or Application lifecycle and is right only if your task should only run when the app is in foreground... but I don't see how this is true. Background threads are AFAIK unrelated to the lifecycle of their creator context. They don't onPause or anything like that.
Service describes a "lifecycle API" that permits external (client) control of the Service. So you can, for example, call stopService and implement kill behavior in Service.onStop instead of writing your own API. But the lifecycle is so trivially-simple that this seems like more complexity, not less. For example, stopService and onStop don't need to be two different methods in a simple local implementation.
I'd especially like to hear of any real use cases where a local service was genuinely preferable to a thread.
First of all service changes killing order of your process.
For a task “fire and forget” all is pretty easy, real fun comes with thread communication. The regular Java mechanisms - pipes, shared memory, blocking queues - are available to Android applications but impose problems for the UI thread because of their tendency to block. Hence, the Android platform defines its own helpers.
BTW, "background" service by default starts in the main thread, for true background work you still have to use threads.

Differences between Asynctasks and Daemons

In this question: Android: AsyncTask vs Service, someone answered
Service is a daemon, AsynkTask is background thread
and someone replied to that answer with:
A service is not a daemon as it doesn't have its own thread of execution.
QUESTION: Since both operate with threads and work in the background, other than the lifespan of each, what are the key differences between Asynctasks and Daemon processes?
I have not met anywhere term Daemon together with Services or AsyncTask. To me Daemon threads are the ones from java which allow JVM to finish even with unfinished Threads. In terms of Android you have no control over your App process - you at most might kill it.
Android service is a Component - this places it near to Activity component. What does it mean? It is managed by system - it has its lifetime during which life cycle methods are being called. Service can be configured to be recreated, or you can make it a foreground (this way system will be less likely to kill it). Since it is a Component you can configure it to be run under separate process. It does not have its own thread of execution by default - it runs on UI thread.
Now AsyncTask is entirely different thing, it is not a Component, so you cannot do anything from above. One thing it has is a background worker thread. Actually AsyncTask is a wrapper around Exeuctors thread pool with some lifecycle methods - like onPreExecute,onPostExecute,... It should not be compared to services, but rather to Loaders.
According to : http://www.linux.org/threads/android-services-and-daemons.7143/
Service:
A "Service" is special software that runs in the background like a
daemon on GNU/Linux. Services doesn't have GUIs. A "started service"
runs in the background until it completes its task, crashes, or is
explicitly closed by the user or application. A "bound service"
persists until no more apps are attached or bound to the service.
AsyncTasks:
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.
Daemon:
A "daemon" is a process that runs in the background *without owning a GUI. Services are usually daemons, and daemons are typically considered services. However, the exact difference between services and daemons is blurred. In general, they can be considered the same entity. However, some people use “daemon” to refer to a piece of software and “service” to refer to the actions and APIs offered by a daemon.

Android Daemon type functionality

If I spawn a thread via AsyncTask from the UI thread, is this thread killed when the UI thread terminates?
My AsyncTask (spawned fom UI) performs operations and then calls the Notification Manager as appropriate (part of my applications functionality). This works well, but notifications cease when the application exits, and I am assuming this is because the UI thread has terminated, therefore so do the children.
I did consider a service (assuming initially it would perform similar to a daemon) but then read that these run on the UI/main thread so would not be persistent across the UI thread termination.
My question really is how can I get the functionality of a daemon spawned from an Android app? I don't need permissions outside the spawning parent process, and it doesn't need to be persistent across reboots.
POSIX API'ish threads through the NDK or am I completely wrong?
Only spent a couple of days with Android so still trying to feel my way around. Many thanks!
Threads execute within a process. Android suspends (for later reuse) or kills an application's process when it's destroyed, which takes all threads with it. So the daemon would have to be a disconnected process, not a thread. Android is deliberately set up to prevent you from starting these (though sub-processes are straightforward with Runtime.exec() and its relatives). I think you can do what you want by fork/exec()'ing in the NDK, but the phone will have to be rooted to run the resulting app, which creates many problems. Not least is that warranty is often voided for a rooted phone.
If I spawn a thread via AsyncTask from the UI thread, is this thread killed when the UI thread terminates?
Not automatically and not immediately. The thread will run to completion, or until Android terminates the process, whichever comes first.
I did consider a service (assuming initially it would perform similar to a daemon) but then read that these run on the UI/main thread so would not be persistent across the UI thread termination.
Services are not really a "daemon" in classic Linux sense. A service is automatically in the background from a UI standpoint. It is not automatically in the background from a threading standpoint. Any work the service does that will take some time should be done on a background thread. The difference is that with a service running, Android will not be as prone to terminate your process quite as quickly.
My question really is how can I get the functionality of a daemon spawned from an Android app?
That depends on what features of a "daemon" you are trying to obtain, which you neglected to describe in your question.
POSIX API'ish threads through the NDK
That will do you no good. Your threads will still be terminated when your process terminates.
I had to implement almost the same functionality: firing notifications form background.
It's rather simple: start a service and spawn a new thread from within the service.
There are many scenario's where Android platform offers some uot-of-the-box goodies where you do not ecessarily have to start threads yourself.
For example:
if your thread should just wait for something you can schedule periodic 'wake up' events with AlarmManager which will take care of running in background
or if you need to synchronize data in background with back-end you can use SyncAdapter API which also takes care of running in background.
As CommonsWare just suggested:
That depends on what features of a "daemon" you are trying to obtain, which you neglected to describe in your question.

why should i use android service instead of java thread

I am confused with android services and java thread.
Please help me to understand in which scenario i should use them.
As per my understanding
Service run in background ,so do thread.
Service is to be used for activities like network operation or playing mp3 in background,so do threads.
So whats actual difference between them and when to use each of them.
Let me give an analogy.
Activities and Service are like projects.
Activities are like external projects. This is what the clients(users) see.
Services are like internal projects. There might be several internal projects for 1 external project or none at all.
You can "pause" external project but the internal project that supports it can still continue.
Main Thread is like the boss in a company
The boss should never be held up by too much work since he shouldn't be late to meetings (UI freezing) or the client(user) will be unhappy.
Threads are like employees in a company.
The more you have, the more things you can do at the same time provided you have enough equipment(CPU speed) for all of them.
Multiple employees can work on the same project at the same time but the boss should really work only on the Activities.
Always: A service of your application is usable not only by other components of your application, but by other applications, too.
A service is for use in not-GUI parts of program.
Mostly: A service is something more independent, than a thread. Service is something more long-living than a thread. Service is something more complex than a thread.
BTW, threads do not run in background only. What runs in foreground, is a thread, too.
I believe the main difference is about Android system attitude. Service is a part of android infrastructure, so android recognizes service as a working part of application and considers killing service as a last option. Moreover, if your service is killed (e.g. because of memory lack) you can say system to restart it automatically, whenever resources available again. Moreover, you can tune up service priority in order to do it as important as foreground activity. As for threads, android does not recognize a thread as important part which must be kept. So usual threads has much more chances to be killed eventually.
For instance If you have an activity which start a working thread and then go background, as android do not recognize thread as a working part, it may think that application do nothing, because no activity or service running and kill the whole app, including the working thread.
Thus when you start a Service, you are telling system something like: "Hi. I'm doing some business here, don't kill me until I finish, please." and Android pay attention to your request.
Services are more analogous to a headless Activity.
The the important piece to understand is that a Service is about managing application lifetime and the ability to keep work running when your Application is not in the foreground (no UI visible). It is also about providing the ability to expose functionality to other apps.
http://developer.android.com/reference/android/app/Service.html#WhatIsAService
Typically when starting a Service you will also start a worker Thread. There are settings in the manifest that can cause a Service to be started in a new Process but generally you do not need to do this, it makes communication with your service more difficult.
Use a just Thread in your Activity when you need to offload work from the UI thread while the application is in the foreground, but this work can stop when you are no longer in the foreground. (It is possible that your app will continue to run when not it foreground but there is no guarantee depending on a number of factors) Generally speaking Android is free to kill your Activity if it is not in the foreground, and if your App process has no Activities or Services it can be killed.
Use a Service with a Thread to do work that will take place while your app is in the background and you want better guarantee about the lifetime.
Use a Service to expose non-UI functionality to other applications.
Android Service don't run in a separate process (by default) and even don't run in a separate thread! It runs in the main thread(UI thread) of the application, therefore if you would like to do something time consuming task in the Service start a separate thread yourself, or use IntentService.
As per Android Developer Guide (http://developer.android.com/guide/components/services.html#Basics) :
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.
Why we need service is to avoid resource crunch.
For example you opening an application after opening an another application so at the time your app added to the background task.
While opening multiple application, ur app may killed by android system. So if ur app has service it won't be killed by the system because service is higher priority , even it may killed the app has service so that we using constant return type in onStartCommand(). Method. That's START_STICKY,START_NOT_STICKY and DELIVER_INTENT.

Necessary to quit a HandlerThread?

My application makes use of a HandlerThread for a few operations shared across components that need to run on a background thread. Most of the time this thread will be in its wait state.
Can I leave this HandlerThread running (waiting) in my application, sending messages to it whenever necessary, but never quitting it via HandlerThread.getLooper().quit()? This could mean that this HandlerThread would continue to exist in its wait state even after all of my application components have been destroyed.
Initially this seemed like a big no to me—something I definitely would not want to do—but I'm not sure now. When Android kills my process, like it will do when it needs to free up CPU time or memory, it'll end this thread along with my UI thread. Additionally, the thread will be waiting, so it wont be consuming any CPU time. And beyond that, my application makes use of many AsyncTasks, which I know utilize a thread pool. From my understanding, AsyncTask utilizes ThreadPoolExecutor, which does not adhere to any application lifecycle callbacks (the threads in the pool when not in use, just sit waiting).
So my question is, can I use a HandlerThread across multiple application components, never (or rarely) quitting it, and leaving it waiting when not in use, without suffering terrible ill effects?
My personal preference is to create a new thread whenever there is a need for it and clean it up when it's done. This way I don't have any problems with multiple components trying to use the same thread at the same time and I keep a "clean ship". Also Android has the nice AsyncTask which makes this easy for you.
That being said, I see no reason why you can't reuse your handlerthread for multiple components, provided you regulate access to the thread AND clean it up properly when your activities are destroyed. If I understand this post correctly, your thread may keep running even if all your activities are terminated because your process may keep on running. To solve this, you can set your thread as a daemon thread. Daemon threads are automatically destroyed when the last non-daemon thread in your application is finished.
BTW, alternatively you also might want to consider using a ThreadPoolExecutor

Categories

Resources