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. We must use Handler, AsynchTask, and Loaders to the Managed background to address them. 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 primary 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 procedure 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 procedure is completed.
For the user to have a good user experience, all the items 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 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 complex approaches are also based on loader, retained Fragment, and service in addition to those classes.
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 send it to the original thread. Data sent using the Handler class can be an instance of the Message or Runnable class.
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 Runnable objects 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 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 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 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.
We can quickly solve this problem if we define an AsynchTask in headless Fragment retained.
To download and use 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 project implementation time, 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 keep a thing if it is in inactivity mode.
Using 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, we need to implement the Application class. To use the Application class, we need to assign the class name 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 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 choices 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 ensure that the amount stored in the preferences increases at each step.
Below we want to provide an example that uses a video download 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 below codes.
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 severe and prolonged processing process, it will suddenly stop running.