Can a background thread exist without the main thread? - android

If I remove the app from the background/recent app list, the UI thread also stops so that system can reclaim the memory associated with the UI. Now consider a case where a PeriodicWorkRequest is triggered which in turn starts a worker (after the app is removed from the background/recent apps list). The worker implicitly runs on a separate background thread and is performing the assigned tasks. But is the UI/Main thread also created along with the worker thread?
An app can exist with no activity. It can have other components like services etc with no UI. In this case, does the UI/Main thread still exist?
Or in any other scenario, can a process exist with no UI/Main thread, just a worker thread?

In android things get complicated really fast.
Android is a fragmented ecosystem and some OEM perform some device alterations that result in different behaviors across devices for example when you close an app instead of doing a grace shutdown it does a kill to provide an immediate effect. even background workers are not very guaranteed, read some more here
Background workers are you best bet.

Related

Why do android services run on the UI thread?

http://developer.android.com/guide/components/services.html
The page starts off by saying services are used to run long standing tasks in the background. Later in the "caution:", it says they are run on the UI thread, and any intensive work should be done in a separate thread, like the code placed inside IntentService's "onHandleIntent" callback.
If the code in onHandleIntent is the service's long standing task, and that runs in a background thread, why do they say a service runs on the UI thread?
There are multiple reasons for this:
UI thread is the way to work with events and binding, and is easier to understand how to interact with the service. That's usually already done on the UI thread, so it would also be easier to initiate functions on the service.
The service is a component without any UI, so it has less memory being used compared to activities, and also has less chance of having memory leaks compared to activities.
The service can run in the foreground, making it have less chance of being killed when the user goes to other apps.
there is also an IntentService, which has a function (called "onHandleIntent" )that runs only on the background thread, if you wish to perform easy background tasks easily.
Instead of forcing you to work in some way, Google lets you decide how&what to perform on the service.
It has its own lifecycle that isn't affected by UI. It's more affected by resource usage and OS decisions, and by the developer's choice of course.

Why android UI runs on the main thread?

Why android UI runs on main thread and not on other threads?
Why is it only dedicated to UI ?
(Some will say its runs services as well, but i dont buy that.
If that were to happen services will end when application exits, since main thread gets killed with process. According to me it runs in OS space( like windows services, i am guessing))
Why cant i change UI from other threads as well? (NOT posting work on UI thread)
Is it the hardware constraint or what ? Why is it designed this way ?
Why cant i change UI from other threads as well?
Android was designed around the mobile CPUs of 2005-2007, which were about 2% of the power of today's CPUs. The synchronization overhead of trying to allow multiple threads to manipulate the UI was deemed to be too high. They used a common approach in those cases: designating a special thread to be the one for UI updates, and failing updates that are attempted on other threads.
Some will say its runs services as well
In general, objects do not run on threads -- methods run on threads.
Lifecycle methods on all Android components are called on the main application thread. So, for a Service, onCreate(), onStartCommand(), onBind(), and onDestroy() are called on the main application thread.
If that were to happen services will end when application exits
Applications in Android do not "exit".
since main thread gets killed with process
When a process terminates, all components in it also "get killed", and so a service that was in that process will go away.

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.

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.

Android Thread Pool has runnables building up without execution after background state

My application has a thread pool that creates 3 simultaneous threads. As I invoke runnables, they are added to my thread pool.
My problem happens when the application goes to the background for a while. Eventually, my threads stop executing the runnables in my pool and the pool just continues to grow. Even if I bring my application back to the foreground, my threads do not start running again.
My theory is that when my application goes to the background that my threads are being killed. I'm not sure by what and I'm also not sure of a good way of determining whether my threads are killed so that I can start them again.
Do you have any suggestions as to something I can look for to determine whether or not a thread has been killed?
You can't use a thread pool to execute code in the background because the Android activity lifecycle won't consider your app to be active, and will kill your process (including all threads) eventually after you lose UI focus. What you want is an Android Service which has a different lifecycle. To do things like this we use a local service with a Handler and a HandlerThread that we can post Runnables into. You'll probably want something similar.
Note: Every time I do this I feel like there must be an easier way, so it might be worth searching if someone has simplified this pattern.

Categories

Resources