What is background mode on an Android phone?
Background work is a useful feature of Android OS
Background mode is a special mode of operation of some operating system components, in which applications and program processes operate without the user’s knowledge and without his direct participation. An example is any messenger. The person seems to have closed it and does not see how it works.
Sometimes it even seems that it is inactive, but this is only at first glance. As soon as the user receives an SMS message, the program processes it, launches or displays a corresponding notification with the text of the message. All this is due to the fact that it was running in the background.
Some examples are not so positive. The Android OS has many pre-installed Google services that are active even when a person is not using them. They are able to “eat up” a decent portion of system resources when running in the background, use limited Internet traffic when downloading updates, and so on. The worst thing is that you won’t be able to delete them without root rights. They can only be turned off.
What is it for
Applications that run in the background most often do not waste much system resources and only connect to the global network if the user is close to a familiar Wi-Fi access point. They regularly interact with the network for any important updates, notify the person about it and ask whether it is worth installing or should they wait.
Important! This is very useful when the user is busy and cannot view the necessary updates of his favorite programs every day. Also, background mode is needed to notify the device owner about new messages, changes and news.
Picture 2 Monitoring processes running in the background
What is the difference between background data transfer?
In addition to the background mode, devices have background data transfer. This function is capable of determining the mode of recording, sending and receiving any data in the background. If this option is activated, then applications, if they have access to the global network, will gain access to it. By disabling the transfer function, a person will allow a program or game to access the network only when it is running and active.
An example would be the same messenger or any other messaging or email service. If they do not have access to background information transfer, then they will not be able to communicate with the server, and will not notify the user about new letters or messages even when there is an Internet connection on the phone. This will happen only after logging into the application, where the person will see several letters or messages at once that came during his “absence”.
A guide to background work in Android. Part 1
There are many articles about background running of applications in Android, but I could not find a detailed guide on how to implement background running - I think because more and more new tools are appearing for such work. Therefore, I decided to write a series of articles about the principles, tools and methods of asynchronous work in Android applications.
There will be several parts:
- Main thread, doing background work using AsyncTask, publishing results to the main thread.
- Difficulties when using AsyncTask. Loaders as one of the ways to avoid them.
- Working in the background using ThreadPools and EventBus.
- RxJava 2 as a method of asynchronous work.
- Coroutines in Kotlin as a method of asynchronous work.
Let's start with the first part.
The first thing to understand is why we even bother with background running in mobile apps.
All Android applications have at least one thread on which the UI is drawn and user input is processed. That's why it is called the UI thread or the main thread.
Every lifecycle method of every component in your application, including Activity, Service, and BroadcastReceiver, runs on the UI thread.
The human eye converts the changing images into smooth video if the frame rate reaches 60 frames per second (yes, that's where the magic number comes from), giving the main thread only 16 ms to render the entire screen.
The duration of a network call can be thousands of times longer.
When we want to download something from the Internet (weather forecast, traffic jams, how much your piece of Bitcoin is worth at the moment), we should not do it from the main thread. Moreover, Android won't let us by throwing NetworkOnMainThreadException.
Seven years ago, when I developed my first Android apps, Google's approach was limited to using AsyncTasks. Let's see how we wrote the code to communicate with the server (pseudo code mostly):
public class LoadWeatherForecastTask extends AsyncTask { public Forecast doInBackground(String... params) { HttpClient client = new HttpClient(); HttpGet request = new HttpRequest(params[0]); HttpResponse response = client.execute(request); return parse(response); } }
The doInBackground() method is guaranteed to be called on a thread other than the main thread. But which one? Depends on the implementation. Here's how Android selects a thread (this is part of the AsyncTask class source code):
@MainThread public final AsyncTask executeOnExecutor(Executor exec, Params... params) { ... mStatus = Status.RUNNING; onPreExecute(); mWorker.mParams = params; exec.execute(mFuture); // <— mFuture contains a Runnable with our doInBackgroundMethod return this; }
Here you can see that execution depends on the Executor parameter. Let's see where it comes from:
public static final Executor SERIAL_EXECUTOR = new SerialExecutor(); ... private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR; ... @MainThread public final AsyncTask execute(Params... params) { return executeOnExecutor(sDefaultExecutor, params); }
As stated here, by default the executor references a thread pool of size 1. This means that all AsyncTasks in your application are run sequentially. This was not always true, since for OS versions from DONUT to HONEYCOMB a pool of size from 2 to 4 was used (depending on the number of processor cores). After HONEYCOMB, AsyncTasks are executed sequentially again by default.
So, the job is done, the bytes have completed their long journey from the other hemisphere. We need to turn them into something understandable and place them on the screen. Luckily, our Activity is right there. Let's put the result in one of our Views.
public class LoadWeatherForecastTask extends AsyncTask { public Forecast doInBackground(String... params) { HttpClient client = new HttpClient(); ... Forecast forecast = parse(response); mTemperatureView.setText(forecast.getTemp()); } }
Oh shit! Another exception!
android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
But we didn't do any network calls on the main thread! Correct, but we tried to break another UI law. The user interface can only be changed from the UI thread. This is true not only for Android, but for almost any system you come across. The reason for this is well explained in Java Concurrency In Practice. In short, the architects wanted to avoid complex locking on changes from multiple sources (user input, binding, and other changes). Using a single thread solves this problem.
Yes, but the UI still needs to be updated. AsyncTask also has a method onPostExecute, which is called on the UI thread:
public void onPostExecutre(Forecast forecast) { mTemperatureView.setText(forecast.getTemp()); }
How does this magic work? Let's look at the source code of AsyncTask:
private void finish(Result result) { if (isCancelled()) { onCancelled(result); } else { onPostExecute(result); } mStatus = Status.FINISHED; } private static class InternalHandler extends Handler { public InternalHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { AsyncTaskResult result = (AsyncTaskResult ) msg.obj; switch (msg.what) { case MESSAGE_POST_RESULT: // There is only one result result.mTask.finish(result.mData[0]); break; } } }
AsyncTask uses a Handler to call onPostExecute in the UI, just like the postOnUiThread method in Android components.
Handler hides the entire interior kitchen. Which one? The idea is to have an infinite loop of checking messages coming to the UI thread and handling them accordingly. Nobody invents bicycles here, although they couldn’t do without pedaling.
For Android, this is implemented by the Looper class, which is passed to the InternalHandler in the code above. The essence of the Looper class is in the loop method:
public static void loop() { ... for (;;) { Message msg = queue.next(); …. msg.target.dispatchMessage(msg); } … }
It simply polls a queue of incoming messages in an endless loop and processes those messages. This means that there must be an initialized instance of Looper on the UI thread. You can access it using a static method:
public static Looper getMainLooper()
By the way, you just learned how to check if your code is being called on the UI thread:
if (Looper.myLooper() === Looper.getMainLooper()) { // we are on the main thread }
If you try to instantiate a Handler in the doInBackground method, you will get a different exception. It will tell you if a Looper is required for the thread. Now you know what this means.
It should be noted that AsyncTask can only be created on the UI thread for the reasons stated above. You might think that AsyncTask is a convenient way to do background work since it hides the complexity and requires little effort to use, but there are a few problems to overcome along the way:
- Each time you need to write a lot of code to solve a relatively simple problem
- AsyncTasks don't know anything about the lifecycle. If handled incorrectly, the best you'll get is a memory leak, the worst you'll get is a crash.
- AsyncTask does not support saving progress state and reusing loading results.
In the next part, I'll look at these problems in detail and show how Loaders can help solve them.
How background mode works on Android
How to remove parental controls on an Android phone
The background mode works in a similar way to the computer version of this technology, because it initially appeared on desktop operating systems and only then migrated to mobile platforms such as Android, iOS or Windows Mobile.
The principle of its operation is to launch programs in hidden mode, in which they do not interfere with the user and do not affect the overall performance of the system, but at the same time actively continue to perform their specific functions:
- OS and software updates.
- Communication with the server to update data on widgets.
- Notifying a person about new SMS messages or news in instant messengers or social networks, and so on.
In total, applications on a phone running Android OS have several operating states:
- Active. The application is actively running.
- Inactive. The program has been launched and is currently in the background, but does not perform any actions due to the device going into sleep mode, etc.
- Background. The program window is not on the current screen, but it still works minimized.
- Stopped. The application does not perform its functions, but is located in the device memory.
- Unlaunched. The program was removed from the list of actively running software or was not launched at all.
Picture 3 Ban on using background
How to enable background mode for apps on iPhone?
Now a few words about Apple mobile gadgets. You can also enable background mode in them. Let's take the iPhone as an example (although by and large it doesn't matter which device will be used).
First you need to download a small free utility called Backgrounder (you can do this on your computer through the Sydia service, since this application is not available in the “native” storage). Next, you should download the installer to your device via iTunes and install the program. It is advisable to create the desired directory manually, copy the installation file into it and install the application there.
Please note: after installation, the application icon will not be created in the list of applets, so it makes no sense to look for it among the installed programs. In addition, in the file manager it is strictly forbidden to delete or move the installation folder, since after this the application will not be recognized by the system.
As for turning on the background mode, everything is simple. When starting a program, when it is completely open, you need to press the Home button and hold it for about 3 seconds. After this, a message about activating the Backgrounder utility will appear and the application will be minimized. To restore the program to its original state, the same button is pressed again, but after this a message appears indicating that the utility is being deactivated, which will be followed by the application exiting the background.
Enable or disable background mode on Android
After getting acquainted with the question of what a background connection is in Android, you need to figure out how to disable the background mode on Android. The user can easily remove some programs from the background or, on the contrary, add them there.
LTE - what is it in an Android phone, how to use it
You cannot completely disable the mode, but you can turn off data transfer. For this:
- Go to your phone's settings.
- Select the “Wireless Networks” or “Mobile Internet” section.
- Find the “Data transfer” item and the “Warnings and limit” parameter.
- They set certain warnings when the software spends more traffic than it should and limit Internet consumption if the limit is exhausted.
Ways to reduce the number of active user processes through the engineering menu
“Killing” some processes running in the background through the engineering menu is extremely inconvenient. Some options for MTK processors do not provide this option at all, so it is recommended to use special applications or clean startup yourself.
Cleaning startup
Not everyone knows how to stop an application on Android. In fact, you can turn the background on and off for each program individually. This will only help until you restart, so you should clean your phone's startup. To do this, you can use a specialized program, since there are no standard solutions for this.
One of them is All-In-One Toolbox, which allows you to speed up your device by removing unnecessary applications that greatly slow down the OS when the phone boots up. This also eliminates the background processes that accompany startup applications.
Important! The same can be done manually, but you will have to delete programs or stop their activity for each separately. To do this, go to the settings, find the section with the software and stop some of the running applications.
Picture 4 Stopping the program allows you to remove it from autorun
How to prevent Xiaomi and Android from terminating programs in the background?
Select the following options: Power saving in background
> select apps > select your app > Background Settings > No restrictions (Choose the next options: Saving Power in The
Background
> Choose apps > select your app >
Background
Settings > No restrictions)
Interesting materials:
How to clear gallery on Android? How to clear Bluetooth history on Android? How to clear Android keyboard history? How to clear keyboard history on Android? How to clear history on an Android tablet? How to clear history in Chrome on Android? How to clear the calendar on Android? How to clear a memory card on Android? How to clear Opera browser cache on Android? How to clear cache and cookies on Android?
How to see a list of processes running in the background on Android
What is cache in an Android phone - detailed information
In order to view the list of applications active and running in the background, you need to download the Greenify program or the solution described above (All-In-One Toolbox). Immediately after logging in, all active processes appear in front of the person with the ability to turn them off and “put them to sleep.”
If you don’t want to download third-party software, you can use the standard solution:
- Go to device settings.
- Find the "Applications" section.
- Select the “Active” tab.
- View the list and, if desired, remove some software from memory by stopping it.
Picture 5 Greenify interface
Advantages and disadvantages of running apps in the background on Android
If we talk about the advantages of working in the background, it is worth highlighting the following:
- Partial automation of software update processes or human notification processes that do not require human intervention.
- Increased functionality of the mobile device and operating system.
- Expansion of the multitasking function, when the device performs several procedures at once.
Important! This approach also has disadvantages, the main one of which is the high energy consumption of the device’s battery. When services are actively running, the phone cannot enter sleep mode and maintain battery life for a couple of hours more.
Picture 6 Working in All-In-One Toolbox
Enterprise mode on Xiaomi (Redmi), what it is and for what purposes it is used
Discussion: 4 comments
- ndaa:
10/27/2020 at 10:09 pmDid not help. Still, notifications do not arrive when the screen is dark. They only come when it's turned on. We are talking about the mail.ru application on xiaomi miui 11
Answer
- Anonymous:
10/27/2020 at 10:44 pm
1. Uninstall or disable the Cleaner application (yellow icon) 2. I quote: “For notifications to work properly, synchronization must be enabled in some applications! For example, notifications for gmail do not work without synchronization! Also, do not forget that synchronization can be enabled ONLY for Wi-Fi, in which case these applications may not work on the mobile Internet. Settings – Synchronization – Wi-Fi only – turn off”
Answer
- Valery:
09.14.2021 at 18:14
What year is this manual? On Readmi 8, the “Security” menu does not have icons such as “Data transfer” and “Power and performance”
Answer
MiMaster:
02.11.2021 at 09:13
Good afternoon, these settings, as I understand from many comments on the site, depend on the firmware and phone model. On my Mi 9 SE they are also in the newest firmware 12.5.1.0. You will probably have to skip these settings, or try to find them another way, somewhere in the MIUI settings. Sorry, I don’t have a Redmi phone in my hands right now, so I can’t give you a more precise answer.
Answer
Which background processes on Android cannot be stopped
If you are guided by the principle that you should stop those applications that spend the largest percentage of battery charge and those that take up the most RAM, then this can sometimes lead to the wrong direction. The thing is that the operating system itself and its components consume the greatest amount of resources and charging. The rest is distributed between system and user applications.
You need to start with programs that have the word “Google” in their name. This must be done calmly and without fanaticism, although any truly important services simply will not allow themselves to be closed and stopped. You should not close the following programs: Google Search, Google Play services, Google Contacts Sync, Google Keyboard, Google Play Store. Everything else, if a person does not use it, can be stopped. In this case, you need to be guided by a list of statistics on the use of system resources and energy consumption.
Picture 7 Analysis of system resource waste
Now the question of how to disable background applications on Android is closed. Today there are many programs for working with the background that allow you to configure, allow or prohibit the launch of certain services or processes.
Internet access in the background
Few people know that the Android operating system and the MIUI shell share the Internet access mode for applications that are in active mode and in the background. So, it is possible to limit access to the Internet for those programs that you are not currently using, which can be very useful, especially if you do not have an unlimited tariff from a cellular operator.
To do this, launch the “Security” on Xiaomi.
Find the item
"Data transfer" . Select Network Connections . Now click on “Three dots” and in the menu that appears “Background connections” .
Disable access for those programs that you want to restrict on the Internet if they are not currently active. This will not only save traffic, but also help reduce battery consumption and increase the autonomy of the smartphone. You should not disable access to all programs indiscriminately; some require it to function adequately. If, after restricting access, you notice that some program began to work poorly, or stopped altogether, access will have to be returned.
Return to content