What is background management in Android apps and how is it done?
8 minute(s) read
Published on: Aug 14, 2021
Updated on: Dec 14, 2021
We can use Handler, AsynchTask and Loaders for background processing in Android apps. When using applications and user interfaces, we may need to manage and control them in the background for better performance. To be able to manage them, we must use Handler, AsynchTask and Loaders to Managed background. If you want to know how to manage them in the background, it is recommended that you follow this tutorial.
Android apps interface thread
The main thread
It should be noted that Android applications input events using a thread of the main user interface, which is sometimes called the main thread. All events are collected in a queue and then a sample of the Looper class is processed by Android.
What is the reason for using concurrency constructs?
It should be noted that in app development (in German: App-Entwicklung ), if the application does not use the same structure, the application code of the Android system will be executed in the main subject and all written commands will be executed one after another. If this operation takes a long time, the application may be blocked until the operation is completed. For example, when we want to download data from the Internet and this operation takes a long time, the application is blocked for a while until the operation is completed.
For the user to have a good user experience, all the items that he can do in running the program and at low speed can be gathered in one program that runs asynchronously. This may be done using the android framework or Java synchronization structures.
Android also supports the Thread class to run asynchronous processing.
The java.util.concurrent package, which also includes the ThreadPools and Executor classes, is provided by the Android system to run background operations.
Here are some things to look for when selecting your Java language thread:
- If the programmer wants to transfer the results, he has obtained to the user interface, he must synchronize with the original thread.
- It should be noted that there is no default for threads to be removed or canceled.
- There is no default process for integration and thread pooling.
- It should be noted that there is no default for managing configuration changes.
Additional structures offered by Android, such as android.os.Handler or AsyncTasks, which can be used for this purpose. It should be noted that in addition to those classes, complex approaches are also based on Loader, retained Fragment and service.
Using the Handler class, you can process and send Runnable messages and objects related to the thread message queue. Of course, you should note that a Handler object with a thread in it can register itself.
For example, if we create a new instance of the Handler class in an activity using the onCreate () method, the resulting Handler object will be able to send it to the original thread. Data sent using the Handler class can be an instance of the Message or Runnable class.
To be able to use the Handler class, we must first inherit it and then rewrite the handleMessage () method to send the message.
Thread can also send messages using the sendMessage (Message) and sendEmptyMessage () methods.
To be able to process Runnable we can use the post () method.
To prevent the creation of a new object, we can use the Handler object in the activity.
In the View class, it is possible to send all objects that are Runnable using the post () method.
Below we provide an example that you can see that the code below shows how to use the Handler using View.
The AsyncTask object can encapsulate the background process and synchronization using the main thread and has the ability to support the reporting of task activities and their progress.
To be able to use the AsynchTask class
To use it, we must inherit it to be able to use it.
If we call the execute () method, AsyncTask will be launched.
The execute () method can be used to call the doInBackground () and onPostExecute () methods.
TypeOfVarArgParams will be sent as input to the doInBackground () method, and this method also has some commands and codes that must be executed in the background thread.
To develop Android (in German: Android-Entwicklung ), the developer can instruct Android to use the executeOnExecutor () method and define them in parallel, or to define AsyncTask.THREAD_POOL_EXECUTOR as the first parameter. It is up to the programmer to do something for Android. Like the following:
Note that changes to config changes are not made automatically by AsyncTask, in other words, if the activity is reconstructed or created, the programmer must manage and control it.
If we define an AsynchTask in headless fragment retained, we can easily solve this problem.
To be able to download and use a content from the web page, we can use the code inserted below.
1- To do this, we create a new project and choose its name de.vogella.android.asynctask.
2- The activity that we consider for this project is called ReadWebpageAsyncTask.
3- In the next step, we will add the android.permission.INTERNET license to the AndroidManifest.xml file.
4- Then we create the layout outline. As below:
5- Then we must modify the Activity as follows. Like the following:
6- After entering the above codes, we can run the project.
7- At the time of project implementation, if we select the desired button, the desired content will be downloaded from the desired web page.
8- Then TextView will be updated.
If you want to save objects, you can use the onRetainNonConfigurationInstance () method, it should be noted that using this method you can save an object if it is in activity mode.
If you use the getLastNonConfigurationInstance () method, you can easily retrieve this object.
The null value for the getLastNonConfigurationInstance () method will be displayed when the after-size activity ends using the finish () method or starts for the first time.
If we want to store several objects in activities, then we need to implement the Application class. To be able to use the Application class, we need to assign the classname to the android: name in our application.
Note that this class is created automatically by Android runtime and will be available until the program is stopped or terminated. We can use this class to be able to use all objects that are shared between activities.
The onTerminate () method in the application class can be used for testing. To access the Application, we can call the getApplication () method in the activity.
Fragments can be used without the use of user interfaces, and the setRetainInstance () method can be used to persist them.
Note that you can dynamically attach a headless fragment to the application while performing background processing and call the setRetainInstance method.
Below is an example that we need to implement a dedicated loader to manage preferences, and it should be noted that the value of preferences also increases at each stage of loading.
1- To do this, we create a new project and name its com.vogella.android.loader.preferences.
2- Activity This new project that we create is MainActivity.
3- Create a class for custom implementation of AsyncTaskLoader and set and manage preferences. Like the following:
4- The codes listed below can also be used to use the loader in the activity.
LoaderManager can automatically call the onLoadFinished () method after each configuration. To set it up, also try to make sure that the amount stored in the preferences increases at each step.
Below we want to provide an example that uses a video download from the Internet and displays a dialog box until the download process is complete.
1- Create a new project and choose its name de.vogella.android.threadslifecycle.
2- The activity of this project is ThreadsLifecycleActivity.
3- Define the required permission to access the Internet in AndroidManifest.xml.
4- Modify and set the AndroidManifest.xml file as the code below.
5- Modify and adjust the main.xml file (layout) according to the codes listed below.
6- Now we must set the activity.
7- After going through the above steps and entering the codes, you must run the program and project. 8- After running, you must press the desired button to start the download process. 9- Ctrl + F11 key combination is a shortcut key that you can use to change and adjust the way and direction of display on the page.
Android has the ability for the programmer to ask the system to report all applications that have a heavy process. Through StrictMode, we can give this command to the Android system, so that if the program has a heavy and long processing process, it will suddenly stop running.
The following code can be used for this:
About our Android and iOS app development services