4

For example, there are a lot of tasks are posted to UI thread as follows.

Handler handler = new Handler(Looper.getMainLooper());

handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        // Some logic to display/update something in UI
    }
}, 5000);

What happens to these tasks when the android application went to the background?

Will these tasks be processed even in the background? Will the complete UI thread be suspended in the background? Or? All the tasks posted to UI thread are suspended?

What happens to UI thread when there are no tasks posted to it after the activity is completely loaded? Will it be suspended, if there are no tasks are in the Looper?

Thanks in advance.

Jitesh Mohite
  • 31,138
  • 12
  • 157
  • 147
Uma Sankar
  • 449
  • 1
  • 8
  • 19
  • if you call the main ui thread from bacjkground service when the app is moved to background or if it is not running, you might face java.lang.IllegalArgumentException: View not attached to window manager error. – Akshay Mar 03 '18 at 06:24

4 Answers4

4

Let's get's dirty with few terms first.

Handler:

A Handler allows communicating back with UI thread from other background thread. This is useful in android as android doesn’t allow other threads to communicate directly with UI thread. In technical terms, it is a way to post Messages or runnable to your associated thread message queue.

so in total there are two task performed by handler

  • to schedule messages and runnables to be executed as some point in the future; and
  • to enqueue an action to be performed on a different thread than your own.

so how to schedule one

post(Runnable),
postAtTime(Runnable, long),
postDelayed(Runnable, Object, long),
sendEmptyMessage(int),
sendMessage(Message), 
sendMessageAtTime(Message, long),
sendMessageDelayed(Message, long).

Looper:

Whatever I mentioned earlier is supported by Looper It has a loop() method which keeps running and listening for the new messages, main thread has one running all the time so you can receive messages from another thread to this thread, if you are creating your own thread and want to listen then don't forget to call prepare() in the thread that is to run the loop.

A simple example

     class LooperThread extends Thread {
      public Handler mHandler;

      public void run() {
          Looper.prepare();

          mHandler = new Handler() {
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };

          Looper.loop();
      }
  }

so now to answer your questions:

1: Things(Threads and so Looper and Handler) keep running until it gets finished by the user or killed by the system.

2: A looper has a loop() method that will process each message in the queue, and block when the queue is empty.

3: In case of updating the UI from background thread make sure app is in the foreground or terminate the background thread in onDestroy() you can quit the looper processing messages using handler.getLooper().quitSafely() or handler.looper.quit() if the handler is attached to the main thread.

It's recommended in case of orientation change or other configuration changes make sure to terminate the background thread.

vikas kumar
  • 10,447
  • 2
  • 46
  • 52
2

UI thread is also known as the Main thread, it's a thread launched by default when you open your application and where all your interactions happen unless you offload them to some other thread. It's not dependent on the visibility of the app, it's running as long as the app lives. It's not suspended by the system.

What happens to UI thread when there are no tasks posted to it after the activity is completely loaded? Will it be suspended, if there are no tasks are in the Looper?

Let's start with the Looper concept. It's very important for understanding how UI thread is working. Looper is a thing that loops in a given thread and handles incoming messages, when there are no tasks it's looping and waiting for new tasks, so, answering your last question, the thread will not be suspended. Looper is designed to keep the thread alive even when there are no tasks. UI thread in Android has it's own Looper by default.

What happens to these tasks when android application gone to background? Will these tasks are processed even in the background? Will the complete UI thread be suspended in background? Or? All the tasks posted to UI thread are suspended?

Going to background does not change anything for the main thread. It's running until the application is killed. So your code scheduled on a handler will just run.

On a side note. The possible problem here is that while activity is in the background it can be killed by the system and you attempt to change UI of it will crash the app (there are a few similar scenarios), but it's not really related to the UI thread.

All in all, the UI thread is not suspended by the framework under any conditions. It just runs and processes everything you give it or waits until new tasks are given to it.

Here you can find the description of the main thread in the official docs.

This is a good SO thread about looper.

TpoM6oH
  • 8,385
  • 3
  • 40
  • 72
  • Your answer holds as long as you're not modifying any UI. If the app is in background and you try to modify UI, it'll throw an IllegalArgumentException. – Trinopoty Apr 11 '18 at 15:33
  • 1
    Not necessarily, it depends on the state of UI component that is modified. It's not really related to the UI thread but more to the lifecycle of views, fragments and activities. – TpoM6oH Apr 11 '18 at 15:42
  • A background app usually has all views destroyed and stuff. Although unrelated, you can only perform UI operations from the UI thread. It's kind of a generalization of many things. – Trinopoty Apr 11 '18 at 15:44
2

What happens to these tasks when android application gone to background?

It will work as intended, No change in the behavior of UI Changes. Only thing is we are not able to see those changes.

Best Solution: Update any view inside your handler when app is in background

eg: TextView and set some text in it, and get this TextView value once the application goes in the foreground.

Will these tasks are processed even in the background? Will the complete UI thread be suspended in background? Or? All the tasks posted to UI thread are suspended?

As I mentioned above this task will work as it is.

The application does not change UI thread when you move to the background, It will remain as it is.

What happens to UI thread when there are no tasks posted to it after the activity is completely loaded? Will it be suspended, if there are no tasks are in the Looper?

Putting it simply, there are Looper threads, for example, UI thread. Such thread has its own Looper, which runs a message loop for the thread. Once message queue is finished it will be finish itself.

UI thread will not be suspended at any cost by itself, Until and unless you write some code to change it :).

Nice to read: Androids Handler.post, what happens exactly

What is the relationship between Looper, Handler and MessageQueue in Android?

Jitesh Mohite
  • 31,138
  • 12
  • 157
  • 147
2

There are many answers concerning the case. I will try to answer exactly to the questions.

What happens to these tasks when android application gone to background?

Nothing is interrupted. Handler will post a Message on MessageQueue on the specified time (unless the hosting process is killed).

Will these tasks are processed even in the background?

From the standpoint of Handler: it doesn't know whether the app is in foreground or background. All it knows, is that it should post a Message some time later.

Will the complete UI thread be suspended in background? Or? All the tasks posted to UI thread are suspended?

What happens to UI thread when there are no tasks posted to it after the activity is completely loaded? Will it be suspended, if there are no tasks are in the Looper?

UI thread won't be "suspended" in any case (unless the hosting process is killed). It's just that it will be idle as a result of MessageQueue being empty - thus no job is needed to be done.

As a side note, refrain from performing UI related actions when app goes to background, because the state of view hierarchy won't be saved correctly. Assume you have performed textView.setText("bob") at a time, when app is in background. Now, the state of this TextView won't be saved, because onSaveInstanceState() has already been executed and won't be executed again, thus if process of the app is killed and recreated (i.e. as a consequence of system resources shortage), then the activity will be restored with a state that it had possessed when onSaveInstanceState() was called. Now user won't see "bob".

You can cancel the scheduled event using Handler#removeCallbacks() API.

Community
  • 1
  • 1
azizbekian
  • 60,783
  • 13
  • 169
  • 249