Wednesday, 14 June 2017

java - Understanding UI thread




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.



Answer



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...