Android UI thread
Большая часть кода Android приложения работает в контексте компонент, таких как Activity, Service, ContentProvider или BroadcastReceiver. Рассмотрим, как в системе Android организованно взаимодействие этих компонент с потоками.
При запуске приложения система выполняет ряд операций: создаёт процесс ОС с именем, совпадающим с наименованием пакета приложения, присваивает созданному процессу уникальный идентификатор пользователя, который по сути является именем пользователя в ОС Linux. Затем система запускает Dalvik VM где создаётся главный поток приложения, называемый также «поток пользовательского интерфейса (UI thread)». В этом потоке выполняются все четыре компонента Android приложения: Activity, Service, ContentProvider, BroadcastReceiver. Выполнение кода в потоке пользовательского интерфейса организованно посредством «цикла обработки событий» и очереди сообщений.
Рассмотрим взаимодействие системы Android с компонентами приложения.
Activity. Когда пользователь выбирает пункт меню или нажимает на экранную кнопку, система оформит это действие как сообщение (Message) и поместит его в очередь потока пользовательского интерфейса (UI thread).
Service. Исходя из наименования, многие ошибочно полагают, что служба (Service) работает в отдельном потоке (Thread). На самом деле, служба работает так же, как Activity в потоке пользовательского интерфейса. При запуске локальной службы командой startService, новое сообщение помещается в очередь основного потока, который выпонит код сервиса.
BroadcastReceiver. При создании широковещательного сообщения система помещает его в очередь главного потока приложения. Главный поток позднее загрузит код BroadcastReceiver который зарегистрирован для данного типа сообщения, и начнёт его выполнение.
ContentProvider. Вызов локального ContentProvider немного отличается. ContentProvider также выполняется в основном потоке но его вызов является синхронным и для запуска кода ContentProvider не использует очередь сообщений.
Исходя из вышесказанного можно заметить, что если главный поток в данный момент обрабатывает пользовательский ввод или выполняет иное действие, выполнение кода, полученного в новом сообщении, начнётся только после завершения текущей операции. Если какая либо операция в одном из компонентов потребует значительного времени выполнения, пользователь столкнётся или с анимацией с рывками, или с неотзывчивыми элементами интерфейса или с сообщением системы «Приложение не отвечает» (ANR).
Для решения данной проблемы используется парадигма параллельного программирования. В Java для её реализации используется понятие потока выполнения (Thread).
Thread: поток, поток выполнения, иногда ещё упоминается как нить, можно рассматривать как отдельную задачу, в которой выполняется независимый набор инструкций. Если в вашей системе только один процессор то потоки выполняются поочередно (но быстрое переключение системы между ними создает впечатление параллельной или одновременной работы). На диаграмме показано приложение, которое имеет три потока выполнения:
Но, к сожалению, для взаимодействия с пользователем, от потока мало пользы. На самом деле, если вы внимательно посмотрите на диаграмму выше, вы поймёте, что как только поток выполнить все входящие в него инструкции он останавливается и перестаёт отслеживать действия пользователя. Чтобы избежать этого, нужно в наборе инструкций реализовать бесконечный цикл. Но возникает проблема как выполнить некое действие, например отобразить что-то на экране из другого потока, иными словами как вклиниться в бесконечный цикл. Для этого в Android можно использовать Android Message System. Она состоит из следующих частей:
Looper: который ещё иногда ещё называют «цикл обработки событий» используется для реализации бесконечного цикла который может получать задания используется. Класс Looper позволяет подготовить Thread для обработки повторяющихся действий. Такой Thread, как показано на рисунке ниже, часто называют Looper Thread. Главный поток Android на самом деле Looper Thread. Looper уникальны для каждого потока, это реализованно в виде шаблона проектирования TLS или Thread Local Storage (любопытные могут посмотреть на класс ThreadLocal в Java документации или Android).
Message: сообщение представляет собой контейнер для набора инструкций которые будут выполнены в другом потоке.
Handler: данный класс обеспечивает взаимодействие с Looper Thread. Именно с помощью Handler можно будет отправить Message с реализованным Runnable в Looper, которая будет выполнена (сразу или в заданное время) потоком с которым связан Handler. Код ниже иллюстрирует использование Handler. Этот код создаёт Activity которая завершиться через определённый период времени.
HandlerThread: написание кода потока реализующего Looper может оказаться не простой задачей, чтобы не повторять одни и те же ошибки система Android включает в себя класс HandlerThread. Вопреки названию этот класс не занимается связью Handler и Looper.
Практическую реализацию данного подхода можно изучить на примере кода класса IntentService, данный класс хорошо подходит для выполнения асинхронных сетевых или иных запросов, так как он может принимать задания одно за другим, не дожидаясь полной обработки текущего, и завершает свою работу самостоятельно.
Выполнение операций в отдельном потоке, не означает, что вы можете делать все что угодно, не влияя на производительность системы. Никогда не забывайте, что написанный вами код работает на машинах, как правило, не очень мощных. Поэтому всегда стоит использовать возможности предоставляемые системой для оптимизации.
Подготовлено на основе материалов AndroidDevBlog
Источник
Difference between Main thread and UI thread in android
If you finding this question on google, document’s android or somewhere, you always view this quote:
Ordinarily, an app’s main thread is also the UI thread. However, under special circumstances, an app’s main thread might not be its UI thread;
The question here is when special circumstances take place? So I’d search and this is a short answer:
@MainThread is the first thread that starts running when you start your application
@UiThread starts from Main Thread for Rendering user Interface
Note: The @MainThread and the @UiThread annotations are interchangeable so methods calls from either thread type are allowed for these annotations.
Still not clear, so I find more and more and have the clearest answer. Turns out, UI and Main threads are not necessarily the same.
Whenever a new application started, public static void main(String[]) method of ActivityThread is being executed. The «main» thread is being initialized there, and all calls to Activity lifecycle methods are being made from that exact thread. In Activity#attach() method (its source was shown above) the system initializes «ui» thread to «this» thread, which is also happens to be the «main» thread. Therefore, for all practical cases «main» thread and «ui» thread are the same.
This is true for all applications, with one exception.
When Android framework is being started for the first time, it too runs as an application, but this application is special (for example: has privileged access). Part of this “specialty” is that it needs a specially configured “main” thread. Since it has already ran through public static void main(String[]) method (just like any other app), its «main» and «ui» threads are being set to the same thread. In order to get «main» thread with special characteristics, system app performs a static call to public static ActivityThread systemMain() and stores the obtained reference. But its «ui» thread is not overridden, therefore «main» and «ui» threads end up being not the same.
However, as stated in the documentation, the distinction is important only in context of some system applications (applications that run as part of OS). Therefore, as long as you don’t build a custom ROM or work on customizing Android for phone manufacturers, I wouldn’t bother to make any distinction at all.
Источник
Android: Looper, Handler, HandlerThread. Part I.
What do you know about threads in Android? You may say «I’ve used AsyncTask to run tasks in background». Nice, but what else? «Oh, I heard something about Handlers , because I used them to show toasts from background thread or to post tasks with delay». That’s definitely better, but in this post I’ll show what’s under the hood.
Let’s start from looking at the well-known AsyncTask class, I bet every Android developer has faced it. First of all, I would like to say that you can find a good overview of AsyncTask class at the official documentation. It’s a nice and handy class for running tasks in background if you don’t want to waste your time on learning how to manage Android threads. The only important thing you should know here is that only one method of this class is running on another thread — doInBackground . The other methods are running on UI thread. Here is a typical use of AsyncTask :
We will use the following straightforward main layout with progress bar for our test:
If progress bar freezes, we are doing heavy job on the UI thread.
We are using AsyncTask here, because it takes some time to get a response from server and we don’t want our UI to be blocked while waiting this response, so we delegate this network task to another thread. There are a lot of posts on why using AsyncTask is bad (if it is an inner class of your Activity / Fragment , it holds an implicit reference to it, which is bad practice, because Activity / Fragment can be destroyed on configuration change, but they will be kept in memory while worker thread is alive; if it is declared as standalone or static inner class and you are using reference to a Context to update views, you should always check whether it is null or not). All tasks on UI thread (which drives the user interface event loop) are executed in sequential manner, because it makes code more predictable — you are not falling into pitfall of concurrent changes from multiple threads, so if some task is running too long, you’ll get ANR (Application Not Responding) warning. AsyncTask is one-shot task, so it cannot be reused by calling execute method on the same instance once again — you should create another instance for a new job.
The interesting part here is that if you try to show a toast from doInBackground method you’ll get an error, something like this:
Why did we face this error? The simple answer: because Toast can be shown only from UI thread, the correct answer: because it can be shown only from thread with Looper . You may ask «What is a Looper ?». Ok, it’s time to dig deeper. AsyncTask is a nice class, but what if the functionality it has is not enough for your needs? If we take a look under the hood of AsyncTask , we will find, that actually it is a box with tightly coupled components: Handler , Runnable , Thread . Let’s work with this zoo. Each of you is familiar with threads in Java , but in Android you may find one more class HandlerThread derived from Thread . The only significant difference between HandlerThread and Thread you should turn your attention to is that the first one incorporates Looper, Thread and MessageQueue. Looper is a worker, that serves a MessageQueue for a current thread. MessageQueue is a queue that has tasks called messages which should be processed. Looper loops through this queue and sends messages to corresponding handlers to process. Any thread can have only one unique Looper , this constraint is achieved by using a concept of ThreadLocal storage. The bundle of Looper + MessageQueue is like a pipeline with boxes.
You may ask «What’s the need in all this complexity, if tasks will be processed by their creators — Handlers ?». There are at least 2 advantages:
- As mentioned above, it helps you to avoid race conditions, when concurrent threads can make changes and when sequential execution is desired.
- Thread cannot be reused after the job is completed while thread with Looper is kept alive by Looper until you call quit method, so you don’t need to create a new instance each time you want to run a job in background.
You can make a Thread with Looper on your own if you want, but I recommend you to use HandlerThread (Google decided to call it HandlerThread instead of LooperThread ): it already has built-in Looper and all pre-setup job will be done for you. And what’s about Handler ? It is a class with 2 basic functions: post tasks to the MessageQueue and process them. By default, Handler is implicitly associated with thread it was instantiated from via Looper , but you can tie it to another thread by explicitly providing its Looper at the constructor call as well. Now it’s time to put all pieces of theory together and look on real example. Let’s imagine we have an Activity and we want to post tasks (in this article tasks are represented by the Runnable interface, what they actually are will be shown in next part) to its MessageQueue (all Activities and Fragments are living on UI thread), but they should be executed with some delay:
Since mUiHandler is tied up to UI thread (it gets UI thread Looper at the default constructor call) and it is a class member, we have an access to it from inner anonymous classes, and therefore can post tasks to UI thread. We are using Thread in example above and its instance cannot be reused if we want to post a new task, we should create a new one. Is there another solution? Yes, we can use a thread with Looper . Here is a slightly modified previous example with HandlerThread instead of Thread , which demonstrates its ability to be reused:
I used HandlerThread in this example, because I don’t want to manage Looper by myself, HandlerThread takes care of it. Once we started HandlerThread we can post tasks to it at any time, but remember to call quit when you want to stop HandlerThread . mWorkerHandler is tied to MyWorkerThread by specifying its Looper . You cannot initialize mWorkerHandler at the HandlerThread constructor call, because getLooper will return null since thread is not alive yet. Sometimes you can find the following handler initialization technique:
Sometimes it will work fine, but sometimes you’ll get NPE at the postTask call stating, that mWorkerHandler is null . Surpise!
Why does it happen? The trick here is in native call needed for new thread creation. If we take a loop on piece of code, where onLooperPrepared is called, we will find the following fragment in the HandlerThread class:
The trick here is that run method will be called only after new thread is created and started. And this call can sometimes happen after your call to the postTask method (you can check it by yourself, just place breakpoints inside postTask and onLooperPrepared methods and take a look which one will be hit first), so you can be a victim of race conditions between two threads (main and background). In the next part what these tasks really are inside MessageQueue will be shown.
Источник