Open In App

What to Use for Background Processing in Android?

By default, application code runs within the main thread. Every statement is therefore executed in sequence. If you perform an extended-lasting operation, the appliance blocks until the corresponding operation has finished. To provide an honest user experience all potentially slow running operations in an Android application should run asynchronously. this will be archived via concurrency constructs of the Java language or of the Android framework. Potentially slow operations are for instance: network, file, and database access, and sophisticated calculations and tasks like them need background processing, let’s dive a little deeper and look at that in detail!

Android modifies the interface and handles input events from one single thread, called the most thread. Android collects all events during this thread during a queue and processes this queue with an instance of the Looper class. The Android Operating System uses the Thread class to perform asynchronous tasks like the ones mentioned above the header image. The java.util.concurrent is also provided by it to perform certain tasks, something which we call background. For instance, by using the ThreadPools and Executor classes.

If you would like to update the interface from a replacement Thread, you would like to synchronize with the most thread. due to these restrictions, Android developers typically use Android-specific code constructs.



Here’s an Example

The RxJava open-source framework allows specifying an observer of an observable stream of knowledge. Once the events happen and are reported finished, the observer is named by the framework. you’ll configure during which thread the observer and observable run.

What Exactly is Background Work?

An app is taken into account to be running within the background as long as each of the subsequent conditions is satisfied:



  1. The app is not in the running state and no foreground services are performed, while the device was being used.
  2. None of the app’s activities (pages) or fragments are currently visible the one using it

A simple glyph to understand this process could be taken from the below Image:

fig.1

Categories of Background Tasks

Background tasks fall under one among the subsequent main categories:

  1. Immediate
  2. Deferred
  3. Exact

To categorize a task, answer the subsequent questions, and traverse the corresponding decision tree in (fig 1:)

Most tasks don’t get to be run at a particular time. Tasks generally leave slight variations in once they run that are supported conditions like network availability and remaining battery. 

These tasks could be used for background processing in Android, Let’s learn more about them in detail:

1. Immediate tasks

For tasks that ought to be executed immediately and wish continued processing, albeit the user puts the appliance in the background or the device restarts, we recommend using WorkManager and its support for long-running tasks. In specific cases, like with media playback or active navigation, you would possibly want to use foreground services directly.

2. Deferred tasks

Every task that’s indirectly connected to user interaction and may run at any time within the future is often deferred. The recommended solution for deferred tasks is WorkManager. The WorkManager makes it quite efficient and easy to schedule the asynchronous and deferrable tasks, even the tasks which need to resume when the phone restarts!

3. Exact tasks

A task that must be executed at a particular point in time and they can use AlarmManager.

Thread & Handler

Initialize the thread with a runnable and then proceed to perform any heavy operation. By default the views have a handler, so you’ll do View.post(). The Handler is that the means of communication between the heavy task running on the created thread and therefore the UI Thread.




Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        final String result = performBlockingTask();
        // GfG Thread Example
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTextView.setText(result);
            }
        });
    }
});
thread.start();

 

 

Problems:

 

IntentService

 

Useful when it’s necessary to run tasks within the background that don’t affect the UI. they’re completely decoupled from view, ie they’re not suffering from the life cycle of the Activity.

 




public class BackgroundServiceGfG extends IntentService {
   
    private static final String TAG = BackgroundServiceGfG.class.getSimpleName();
 
    public BackgroundServiceGfG() {
        super(TAG );
    }
 
    @Override
    protected void onHandleIntent(Intent intent) {
        blockingTask();
    }
}

 
 

GeekTip: It must be declared within the AndroidManifest.xml a bit like the other Service. It can then be pushed by simply sending an intent (it can even include any parameter!)

 

Problems:

 

AsyncTask

 

Run instructions within the background and synchronize again with the most Thread. Useful for brief background operations. Read More here.

 




new AsyncTask<Void, Void, String>() {
    @Override
    protected void onPreExecute() {
        // Creating a Sample Async Task
    }
 
    @Override
    protected String doInBackground(Void... voids) {
        return performBlockingTask();
    }
 
    @Override
    protected void onProgressUpdate(Integer... progress) {
        mProgessBar.setProgress(progress);
    }
 
    @Override
    protected void onPostExecute(String result) {
        mTextView.setText(result);
    }
    
}.execute();

 

 

Problems:

 

 

Each AsyncTask instance is often executed only/just one time.

 

Conclusion

 

With this, we conclude our article on Background Processing, as you could see there are certain issues and problems with the methods, so choosing the right one (suiting your need) should be an easy task!

 


Article Tags :