How does the OS determine which threads to suspend? - android

The title isn't good, so please read this description to understand what i mean.
I created a background service that i want to run for a long time, by definition services on android can run even if user switch the app or even closes it.
My question is: how does android management system knows which threads to keep and which to wipe when the app goes background and the only running thing is the service?
My service runs by default on the mainthread, so when i want to perform a long task i do:
AsyncTask.THREAD_POOL_EXECUTOR.execute(runnable);
is that right? can i use this default threadpool created by android or the service must explicitly creates the thread in order to the system knows that thread must survive even if the app goes background?

how does android management system knows which threads to keep and which to wipe when the app goes background and the only running thing is the service?
Android does not "wipe" any threads. Android terminates processes to free up system RAM, not threads.
is that right?
I would recommend using your own Executor, RxJava, or Kotlin coroutines, over using the executor in AsyncTask. That is because I expect AsyncTask to be deprecated sometime, as it is "old school".
However, beyond that, what you are doing sounds fine.

Related

Android Using a Thread for Background Jobs

I have read many posts state that doze mode killed a running service at a particular moment e.x link or that they want to execute a long running thread.
I can't understand why you should use a service to do a background job that you know that in some point it will stop eventually.
For instance:
You could use a simple Thread:
new Thread(new Runnable).start()
and do some work in it. Using this:
In combination with a wake lock, device wont sleep and thread will keep running.
No doze mode restriction (except network but lets say we do local stuff)
So you can do background work with no restriction whatsoever. Although you should use services for these reasons link.
Is this another way (not better of course but a way nonetheless) of doing a background work? Am I wrong?
There are a lot of ways to do a background job aside of services check this link it may help you pick the best option for your work :
Job Scheduler vs Background Service
And services as #TheWanderer said will continue to work event after the app is closed for a period of time unlike a simple thread that will end immediately when the app is closed.
Read this part in the link that you linked
Services are given higher priority than other Background processes and
hence it’s less likely that Android will terminate it. Although it can
be configured to restart once there is ample resources available
again. You should go through the different processes and their
priority/important level in the documentation on processes and
threads. Assigning them the same priority as foreground activities is
definitely possible in which case it’ll need to have a visible
notification active (generally used for Services playing music).
If you are running a background thread that you start from an Activity, Android does not know that you are doing background work in the OS Process that is hosting your Activity. Android can kill the OS Process hosting your Activity at pretty much any time. If the user presses the HOME button or takes a phone call or opens a notification and goes to another application, Android can kill off the OS Process at any time. When the user returns to your application, Android will create a new OS Process and recreate all the relevant activities, but your background thread is hopelessly lost. This is the reason that Android has services.
If you start a Service to perform your background processing, the Service will also start background threads, but these are controlled. Your Service tells Android what to do if it kills the Service while it is processing an Intent. Your Service can therefore be informed and restart (or continue) the background processing as necessary. You can also run the Service in a different OS Process from the OS Process running your activities. This will prevent Android from killing the Service if the user removes your app from the list of recent tasks.
With newer Android SDKs there are other mechanisms you can use, like JobScheduler.

Background threads created are not killed by Android O

While testing the background execution limits as stated here I created a thread in my service. Something like this :
// spawn own thread
HandlerThread thread = new HandlerThread("TestServiceThread");
thread.start();
The service is started by the usual pre Oreo startService.
What I noticed while debugging in android device monitor is that the threads I create continue to live long and healthy and execute normally. Can this be a workaround to keep abusing system resources and not do things via foreground services or jobs ? or is it just a chase against the framework which will soon end ? Any comments ?
I wouldn't expect that to change. Its impossible (not just in Android, its theoretically impossible) to safely kill a thread without the thread helping out. Otherwise you could kill the thread in a condition where other threads will deadlock, have inconsistent data, or the app may just not function. That's why thread.stop() is deprecated- because there is no way to make it safe. And that's why you interrupt a thread instead, and the thread needs to monitor isInterrupted and exit cleanly.
I would be careful with this kind of approach.
Although Gabe Sechan's answer is quite valid, the danger of relying on this working is too high to pursue this. Google are clearly out to get any app that tries to do background execution and abuses the user's battery and for good reason in my opinion. Some apps just don't respect a user's battery at all.
The documentation clearly states:
An app is considered to be in the foreground if any of the following
is true:
It has a visible activity, whether the activity is started or paused.
It has a foreground service. Another foreground app is connected to
the app, either by binding to one of its services or by making use of
one of its content providers. For example, the app is in the
foreground if another app binds to its: IME Wallpaper service
Notification listener Voice or text service If none of those
conditions is true, the app is considered to be in the background.
Source:
https://developer.android.com/about/versions/oreo/background.html#services
Although it's not safe to kill a thread due to all the reasons mentioned by Gabe, Android could well kill the app off entirely (ala kill -9). I would imagine that any deadlocks would be handled by Android (not a trivial task I'm sure). Data corruption would be considered as the app's fault for not handling background execution properly.
It's a bit of a risk for Android but they've probably weighed it up and decided this is the way to go.
Also, take care of this:
Note: By default, these restrictions only apply to apps that target
Android 8.0 (API level 26) or higher. However, users can enable most
of these restrictions for any app from the Settings screen, even if
the app targets an API level lower than 26.
Source: https://developer.android.com/about/versions/oreo/background.html#overview

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.

Android program to work in the back ground (service ?)

I finished an Android program. It uses thread. No service.
I would like when the user closes the program with the BACK button
to give an option for the program to keep working in the back ground, or part of it.
The question is what is the best way to take and how to implement it.Is SERVICE the only
way to go or there is another way?
I have seen tracking programs do it.
Yes , service is the best choice of all to keep your application running in the background.
But also remember that keeping a service running does not mean its guaranteed to not getting killed.If resources are too low, Android system might kill your service too.
Please go through this and check Process lifecycle under it.
As you know ,phones are very limited in the amount of resources, its ideal that you do minimum amount of work in the background and also if you require to download something in the background after a specific time consider using AlarmManager instead of polling in the service.One purpose of creating a thread is not blocking the UI.Remember that a Service runs in the UI thread itself,So starting a thread inside a service is a better choice if you want to have long running background work.

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

Categories

Resources