What is android main thread

Содержание
  1. Difference between Main thread and UI thread in android
  2. Многопоточность в Android. Все что вам нужно знать. Часть 1 — Введение
  3. Многозадачность в Android
  4. Компоненты многопоточности, которые присоединяются к активности / фрагменту
  5. AsyncTask
  6. Загрузчики
  7. Компоненты многопоточности, которые не присоединяются к активности / фрагменту
  8. Service
  9. IntentService
  10. Android Threading: All You Need to Know
  11. Threading in Android
  12. Threading Components that Attach to an Activity/Fragment
  13. AsyncTask
  14. Loaders
  15. Threading Components that Don’t Attach to an Activity/Fragment
  16. Service
  17. IntentService
  18. Seven Threading Patterns in Android
  19. Use Case No. 1: Making a request over network without requiring a response from the server
  20. Option 1: AsyncTask or loaders
  21. Option 2: Service
  22. Option 3: IntentService
  23. Use Case No. 2: Making a network call, and getting the response from the server
  24. Option 1: Service or IntentService
  25. Option 2: AsyncTask or loaders
  26. Option 3: RxJava
  27. Use Case No. 3: Chaining network calls
  28. Option 1: AsyncTask or loaders
  29. Option 2: RxJava using flatMap
  30. Use Case No. 4: Communicate with the UI thread from another thread
  31. Option 1: RxJava inside the service
  32. Option 2: BroadcastReceiver
  33. Option 3: Using Handler
  34. Option 3: Using EventBus
  35. Use Case No. 5: Two-way communication between threads based on user actions
  36. Option 1: Using EventBus
  37. Option 2: Using BoundService
  38. Use Case No. 6: Executing actions in parallel and getting results
  39. Option 1: Using RxJava
  40. Option 2: Using native Java components
  41. Use Case #7: Querying local SQLite database
  42. Option 1: Using RxJava
  43. Option 2: Using CursorLoader + ContentProvider
  44. There’s no Silver Bullet Solution to Threading in Android

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. Все что вам нужно знать. Часть 1 — Введение

13.08.2017 в 11:40

Каждый Android разработчик, в тот или иной момент сталкивается с необходимостью иметь дело с потоками в своем приложении.

Когда приложение запускается, оно создает первый поток выполнения, известный как основной поток или main thread. Основной поток отвечает за отправку событий в соответствующие виджеты пользовательского интерфейса, а также связь с компонентами из набора инструментов Android UI.

Чтобы ваше приложение сохраняло отзывчивость, важно избегать использования основного потока для выполнения любой операции, которая может привести к его блокировке.

Сетевые операции и обращения к базе данных, а также загрузка определенных компонентов, являются типичными примерами операций, которые не следует выполнять в основном потоке. Когда они вызваны в главном потоке, они вызваны синхронно, что означает, что пользовательский интерфейс не будет ни на что реагировать до завершения операции. По этой причине, они обычно выполняются в отдельных потоках, что позволяет избежать блокировки пользовательского интерфейса во время выполнения (т. е. они выполняются асинхронно из UI).

Android предоставляет множество способов создания и управления потоками, и множество сторонних библиотек, которые делают управление потоками гораздо более приятным.

В этой статье вы узнаете о некоторых распространенных сценариях в Android разработке, где многопоточность становится важной, и некоторые простые решения, которые могут быть применены к этим сценариям, и многое другое.

Многозадачность в Android

В Android вы можете классифицировать все компоненты потоков на две основные категории:

Потоки связанные с активностью / фрагментом. Эти потоки привязаны к жизненному циклу активности / фрагмента и завершаются сразу после их уничтожения.

Потоки не связанные с активностью / фрагментом. Эти потоки могут продолжать работать за пределами жизни активности / фрагмента (если есть), из которых они были созданы.

Компоненты многопоточности, которые присоединяются к активности / фрагменту

AsyncTask

AsyncTask это наиболее основной Android компонент для организации потоков. Он прост в использовании и может быть хорошей основой для вашего сценария.

Однако, AsyncTask не подойдет, если вам нужен отложенный запуск задачи, после завершения работы вашей активности / фрагмента. Стоит отметить, что даже такая простая вещь, как вращение экрана может вызвать уничтожение активности.

Загрузчики

Загрузчики могут решить проблемы, упомянутые выше. Загрузчик автоматически останавливается, когда уничтожается активность и перезапускает себя, после пересоздания активности.

В основном есть два типа загрузчиков: AsyncTaskLoader и CursorLoader . О загрузчике CursorLoader вы узнаете далее в этой статье.

AsyncTaskLoader похож на AsyncTask , но немного сложнее.

Компоненты многопоточности, которые не присоединяются к активности / фрагменту

Service

Service это компонент, который полезен для выполнения длинных (или потенциально длительных) операций без какого-либо пользовательского интерфейса.

Читайте также:  Системные настройки звука для андроид

Service работает в основном потоке своего процесса; не создает свой собственный поток и не запускается в отдельном процессе, если вы это не указали.

Используя Service вы обязаны остановить его, когда его работа будет завершена, вызвав методы stopSelf() или stopService() .

IntentService

IntentService работает в отдельном потоке и автоматически останавливается после завершения работы.

IntentService обычно используется для коротких задач, которые не обязательно должны быть привязаны к какому-либо пользовательскому интерфейсу.

Источник

Android Threading: All You Need to Know

Android provides many ways of creating and managing threads, and third-party libraries exist to make that even easier. However, with so many options, choosing the right approach can be quite confusing. In this article, Toptal Freelance Software Engineer Eliran Goshen discusses some common scenarios in Android development that involve threading and how each of the scenarios can be dealt with.

Every Android developer, at one point or another, needs to deal with threads in their application.

When an application is launched in Android, it creates the first thread of execution, known as the “main” thread. The main thread is responsible for dispatching events to the appropriate user interface widgets as well as communicating with components from the Android UI toolkit.

To keep your application responsive, it is essential to avoid using the main thread to perform any operation that may end up keeping it blocked.

Network operations and database calls, as well as loading of certain components, are common examples of operations that one should avoid in the main thread. When they are called in the main thread, they are called synchronously, which means that the UI will remain completely unresponsive until the operation completes. For this reason, they are usually performed in separate threads, which thereby avoids blocking the UI while they are being performed (i.e., they are performed asynchronously from the UI).

Android provides many ways of creating and managing threads, and many third-party libraries exist that make thread management a lot more pleasant. However, with so many different approaches at hand, choosing the right one can be quite confusing.

In this article, you will learn about some common scenarios in Android development where threading becomes essential and some simple solutions that can be applied to those scenarios and more.

Threading in Android

In Android, you can categorize all threading components into two basic categories:

  1. Threads that are attached to an activity/fragment: These threads are tied to the lifecycle of the activity/fragment and are terminated as soon as the activity/fragment is destroyed.
  2. Threads that are not attached to any activity/fragment: These threads can continue to run beyond the lifetime of the activity/fragment (if any) from which they were spawned.

Threading Components that Attach to an Activity/Fragment

AsyncTask

AsyncTask is the most basic Android component for threading. It’s simple to use and can be good for basic scenarios.

AsyncTask , however, falls short if you need your deferred task to run beyond the lifetime of the activity/fragment. It is worth noting that even something as simple as screen rotation can cause the activity to be destroyed.

Loaders

Loaders are the solution for the problem mentioned above. Loaders can automatically stop when the activity is destroyed, and can also restart themselves after the activity is recreated.

There are mainly two types of loaders: AsyncTaskLoader and CursorLoader . You will learn more about CursorLoader later in this article.

AsyncTaskLoader is similar to AsyncTask , but a bit more complicated.

Threading Components that Don’t Attach to an Activity/Fragment

Service

Service is a component that is useful for performing long (or potentially long) operations without any UI.

Service runs in the main thread of its hosting process; the service does not create its own thread and does not run in a separate process unless you specify otherwise.

With Service , it is your responsibility to stop it when its work is complete by calling either the stopSelf() or the stopService() method.

IntentService

Like Service , IntentService runs on a separate thread, and stops itself automatically after it completes its work.

IntentService is usually used for short tasks that don’t need to be attached to any UI.

Seven Threading Patterns in Android

Use Case No. 1: Making a request over network without requiring a response from the server

Sometimes you may want to send an API request to a server without needing to worry about its response. For example, you may be sending a push registration token to your application’s back-end.

Since this involves making a request over the network, you should do it from a thread other than the main thread.

Option 1: AsyncTask or loaders

You can use AsyncTask or loaders for making the call, and it will work.

However, AsyncTask and loaders are both dependent on the lifecycle of the activity. This means you will either need to wait for the call to execute and try to prevent the user from leaving the activity, or hope that it will execute before the activity is destroyed.

Option 2: Service

Service may be a better fit for this use case since it isn’t attached to any activity. It will therefore be able to continue with the network call even after the activity is destroyed. Plus, since the response from the server is not needed, a service wouldn’t be limiting here, either.

However, since a service will begin running on the UI thread, you will still need to manage threading yourself. You will also need to make sure that the service is stopped once the network call is complete.

This would require more effort than should be necessary for such a simple action.

Option 3: IntentService

This, in my opinion, would be the best option.

Since IntentService doesn’t attach to any activity and it runs on a non-UI thread, it serves our needs perfectly here. Moreover, IntentService stops itself automatically, so there is no need to manually manage it, either.

Use Case No. 2: Making a network call, and getting the response from the server

This use case is probably a bit more common. For example, you may want to invoke an API in the back-end and use its response to populate fields on the screen.

Option 1: Service or IntentService

Although a Service or an IntentService fared well for the previous use case, using them here wouldn’t be a good idea. Trying to get data out of a Service or an IntentService into the main UI thread would make things very complex.

Читайте также:  Оптимизер про для андроид

Option 2: AsyncTask or loaders

At first blush, AsyncTask or loaders would appear to be the obvious solution here. They are easy to use—simple and straightforward.

However, when using AsyncTask or loaders, you’ll notice that there is a need to write some boilerplate code. Moreover, error handling becomes a major chore with these components. Even with a simple networking call, you need to be aware of potential exceptions, catch them, and act accordingly. This forces us to wrap our response in a custom class containing the data, with possible error information, and a flag indicates if the action was successful or not.

That’s quite a lot of work to do for every single call. Fortunately, there is now a much better and simpler solution available: RxJava.

Option 3: RxJava

You may heard about RxJava, the library developed by Netflix. It’s almost magic in Java.

RxAndroid lets you use RxJava in Android, and makes dealing with asynchronous tasks a breeze. You can learn more about RxJava on Android here.

RxJava provides two components: Observer and Subscriber .

An observer is a component that contains some action. It performs that action and returns the result if it succeeds or an error if it fails.

A subscriber, on the other hand, is a component that can receive the result (or error) from an observable, by subscribing to it.

With RxJava, you first create an observable:

Once the observable has been created, you can subscribe to it.

With the RxAndroid library, you can control the thread in which you want to execute the action in the observable, and the thread in which you want to get the response (i.e., the result or error).

You chain on the observable with these two functions:

Schedulers are components that execute the action in a certain thread. AndroidSchedulers.mainThread() is the scheduler associated with the main thread.

Given that our API call is mRestApi.getData() and it returns a Data object, the basic call can look like this:

Without even going into other benefits of using RxJava, you can already see how RxJava allows us to write more mature code by abstracting away the complexity of threading.

Use Case No. 3: Chaining network calls

For network calls that need to be performed in sequence (i.e., where each operation depends upon the response/result of the previous operation), you need to be particularly careful about generating spaghetti code.

For example, you may have to make an API call with a token that you need to fetch first through another API call.

Option 1: AsyncTask or loaders

Using AsyncTask or loaders will almost definitely lead to spaghetti code. The overall functionality will be difficult to get right and will require a tremendous amount of redundant boilerplate code throughout your project.

Option 2: RxJava using flatMap

In RxJava, the flatMap operator takes an emitted value from the source observable and returns another observable. You can create an observable, and then create another observable using the emitted value from the first one, which will basically chain them.

Step 1. Create the observable that fetches the token:

Step 2. Create the observable that gets the data using the token:

Step 3. Chain the two observables together and subscribe:

Note that use of this approach is not limited to network calls; it can work with any set of actions that needs to be run in a sequence but on separate threads.

All of the use cases above are quite simple. Switching between threads only happened after each finished its task. More advanced scenarios—for example, where two or more threads need to actively communicate with each other—can be supported by this approach as well.

Use Case No. 4: Communicate with the UI thread from another thread

Consider a scenario where you would like to upload a file and update the user interface once it is complete.

Since uploading a file can take a long time, there is no need to keep the user waiting. You could use a service, and probably IntentService , for implementing the functionality here.

In this case, however, the bigger challenge is being able to invoke a method on the UI thread after the file upload (which was performed in a separate thread) is complete.

Option 1: RxJava inside the service

RxJava, either on its own or inside an IntentService , may not be ideal. You will need to use a callback-based mechanism when subscribing to an Observable , and IntentService is built to do simple synchronous calls, not callbacks.

On the other hand, with a Service , you will need to manually stop the service, which requires more work.

Option 2: BroadcastReceiver

Android provides this component, which can listen to global events (e.g., battery events, network events, etc.) as well as custom events. You can use this component to create a custom event that is triggered when the upload is complete.

To do this, you need to create a custom class that extends BroadcastReceiver , register it in the manifest, and use Intent and IntentFilter to create the custom event. To trigger the event, you will need the sendBroadcast method.

This approach is a viable option. But as you have noticed, it involves some work, and too many broadcasts can slow things down.

Option 3: Using Handler

A Handler is a component that can be attached to a thread and then made to perform some action on that thread via simple messages or Runnable tasks. It works in conjunction with another component, Looper , which is in charge of message processing in a particular thread.

When a Handler is created, it can get a Looper object in the constructor, which indicates which thread the handler is attached to. If you want to use a handler attached to the main thread, you need to use the looper associated with the main thread by calling Looper.getMainLooper() .

In this case, to update the UI from a background thread, you can create a handler attached to the UI thread, and then post an action as a Runnable :

This approach is a lot better than the first one, but there is an even simpler way to do this…

Читайте также:  Что такое калибровка для андроид

Option 3: Using EventBus

EventBus , a popular library by GreenRobot, enables components to safely communicate with one another. Since our use case is one where we only want to update the UI, this can be the simplest and safest choice.

Step 1. Create an event class. e.g., UIEvent .

Step 2. Subscribe to the event.

Step 3. Post the event: EventBus.getDefault().post(new UIEvent());

With the ThreadMode parameter in the annotation, you are specifying the thread on which you would like to subscribe for this event. In our example here, we are choosing the main thread, since we will want the receiver of the event to be able to update the UI.

You can structure your UIEvent class to contain additional information as necessary.

In the activity/fragment:

Using the EventBus library , communicating between threads becomes much simpler.

Use Case No. 5: Two-way communication between threads based on user actions

Suppose you are building a media player and you want it to be able to continue playing music even when the application screen is closed. In this scenario, you will want the UI to be able to communicate with the media thread (e.g., play, pause, and other actions) and will also want the media thread to update the UI based on certain events (e.g. error, buffering status, etc).

A full media player example is beyond the scope of this article. You can, however, find good tutorials here and here.

Option 1: Using EventBus

You could use EventBus here. However, it is generally unsafe to post an event from the UI thread and receive it in a service. This is because you have no way of knowing whether the service is running when you have sent the message.

Option 2: Using BoundService

A BoundService is a Service that is bound to an activity/fragment. This means that the activity/fragment always knows if the service is running or not and, in addition, it gets access to the service’s public methods.

To implement it, you need to create a custom Binder inside the service and create a method that returns the service.

To bind the activity to the service, you need to implement ServiceConnection , which is the class monitoring the service status, and use the method bindService to make the binding:

You can find a full implementation example here.

To communicate with the service when the user taps on the Play or Pause button, you can bind to the service and then call the relevant public method on the service.

When there is a media event and you want to communicate that back to the activity/fragment, you can use one of the earlier techniques (e.g., BroadcastReceiver , Handler , or EventBus ).

Use Case No. 6: Executing actions in parallel and getting results

Let’s say you are building a tourist app and you want to show attractions on a map fetched from multiple sources (different data providers). Since not all of the sources may be reliable, you may want to ignore the ones that have failed and continue to render the map anyway.

To parallelize the process, each API call must take place in a different thread.

Option 1: Using RxJava

In RxJava, you can combine multiple observables into one using the merge() or concat() operators. You can then subscribe on the “merged” observable and wait for all results.

This approach, however, won’t work as expected. If one API call fails, the merged observable will report an overall failure.

Option 2: Using native Java components

The ExecutorService in Java creates a fixed (configurable) number of threads and executes tasks on them concurrently. The service returns a Future object that eventually returns all results via the invokeAll() method.

Each task you send to the ExecutorService should be contained in Callable interface, which is an interface for creating a task that can throw an exception.

Once you get the results from invokeAll() , you can check every result and proceed accordingly.

Let’s say, for example, that you have three attraction types coming in from three different endpoints and you want to make three parallel calls:

This way, you are running all of the actions in parallel. You can, therefore, check for errors in each action separately and ignore individual failures as appropriate.

This approach is easier than using RxJava. It is simpler, shorter, and doesn’t fail all actions because of one exception.

Use Case #7: Querying local SQLite database

When dealing with a local SQLite database, it is recommended that the database be used from a background thread, since database calls (especially with large databases or complex queries) can be time consuming, resulting in the UI freezing.

When querying for SQLite data, you get a Cursor object that can then be used to fetch the actual data.

Option 1: Using RxJava

You can use RxJava and get the data from the database, just as we’re getting data from our back-end:

You can use the observable returned by getLocalDataObservable() as follows:

While this is certainly a good approach, there is one that is even better, since there is a component that is built just for this very scenario.

Option 2: Using CursorLoader + ContentProvider

Android provides CursorLoader , a native component for loading SQLite data and managing the corresponding thread. It’s a Loader that returns a Cursor , which we can use to get the data by calling simple methods such as getString() , getLong() , etc.

CursorLoader works with the ContentProvider component. This component provides a plethora of real-time database features (e.g., change notifications, triggers, etc.) that enables developers to implement a better user experience much more easily.

There’s no Silver Bullet Solution to Threading in Android

Android provides many ways to handle and manage threads, but none of them are silver bullets.

Choosing the right threading approach, depending on your use case, can make all the difference in making the overall solution easy to implement and understand. The native components fit well for some cases, but not for all. The same applies for fancy third-party solutions.

I hope you will find this article useful when working on your next Android project. Share with us your experience of threading in Android or any use case where the above solutions work well—or don’t, for that matter—in the comments below.

Источник

Оцените статью