Android UI threads and non-UI threads

Source: Internet
Author: User

UI threading and Android's single-threaded model principles

When the app starts, the system creates a main thread (main thread).

This main thread is responsible for distributing events to the UI component (including drawing events), and also in this main thread, your app and the Android UI components (the component from the Android UI Toolkit Android.widget and Android.view packages) interact.

So the main thread is also called the UI thread .

The system does not create a separate thread for each component, the UI component in the same process is instantiated in the UI thread, and the system's call to each component is distributed from the UI thread .

As a result, methods that respond to system callbacks, such as onkeydown () and various life-cycle callbacks that respond to user actions, are always run in the UI thread.

When the app does some heavy work (intensive), the performance of the single-threaded model will be poor unless you reasonably implement it.

In particular, if all the work is done on the UI thread, doing more time-consuming work such as accessing the network or querying the database will block the UI thread , causing the event to stop distributing (including drawing events). For the user, the app looks like it's stuck, and worse, if the UI thread blocked for too long (about 5 seconds), the user sees a dialog box for the ANR(application not responding).

In addition, Andoid UI Toolkit is not thread-safe, so you cannot manipulate UI components from a non-UI thread. You have to put all the UI actions on the UI thread, so Android's single-threaded model has two principles:

  1. Do not block the UI thread.

  2. Do not access the Android UI Toolkit(mainly the components in these two packages: and Android.view) outside the UI thread android.widget .

Working with worker threads

According to the two principles of the single-threaded model, first of all, to ensure that the application's responsiveness, not blocking the UI thread, so when your operation is not the kind of instant (not instantaneous), you should put them into the separate line approached (called background or call worker thread ).

For example, after clicking the button, download a picture and show it in ImageView:

public void OnClick (View v) {    new Thread (new Runnable () {public        void run () {            Bitmap B = loadimagefromnetwork ( "Http://example.com/image.png");            Mimageview.setimagebitmap (b);        }    }). Start ();}

This code handles the network operation with a new thread, but it violates the second rule:

  Do not access the Android UI Toolkit from outside the UI thread.

Accessing the UI component from a non-UI thread can result in undefined and unpredictable behavior .

  To solve this problem, Android provides some ways to access the UI thread from other threads:

    • Activity.runonuithread (Runnable)
    • View.post (Runnable)
    • View.postdelayed (Runnable, long)

For example, the above code can be changed:

public void OnClick (View v) {    new Thread (new Runnable () {public        void run () {            final Bitmap Bitmap = LOADIMAGEF Romnetwork ("Http://example.com/image.png");            Mimageview.post (New Runnable () {public                void run () {                    mimageview.setimagebitmap (bitmap);}}            );    } ). Start ();}

This is a thread-safe way to change.

However, when the operation becomes complex, the code becomes very complex, and in order to handle the more complex interactions between the non-UI thread and the UI thread, consider using one in the worker thread Handler to handle the messages coming from the UI thread.

You can also inherit this class Asynctask.

Communicating with the UI Thread

  only objects in the UI thread can manipulate the alignment in the UI thread, and in order to transfer data from non-UI threads to the UI thread, a handler is used to run in the UI thread.

Handler is part of managing threads in the Android framework, and a handler object is responsible for receiving messages and processing messages.

You can create a handler for a new thread, or you can create a handler and then connect it to a wired thread.

  If you connect a handler to your UI thread, the code that processes the message will be executed in the UI thread.

You can instantiate the handler object in the constructor of the class where you created the thread pool, and then store the object with a global variable.

To connect to the UI thread, you should use Handler(Looper) this construction method when instantiating handler.

This construction method uses an Looper object, which is another part of the framework that the Android system threads to manage.

  When you Looper create a handler with a specific instance, the handler runs in this Looper thread.

In handler, the method is to be written handleMessage() . The Android system calls this method when a new message is received by the appropriate thread that handler manages .

  All handler objects of a particular thread will receive the same method. (This is a "one-to-many" relationship).

Resources

Official training: Communicating with the UI thread:

Http://developer.android.com/training/multiple-threads/communicate-ui.html

Guides:processes and Threads

Http://developer.android.com/guide/components/processes-and-threads.html

Class Reference:

Http://developer.android.com/reference/android/os/Looper.html

Http://developer.android.com/reference/android/os/Handler.html

Http://developer.android.com/reference/android/os/HandlerThread.html

Blog:

Android threads are used to update the UI----thread, Handler, Looper, TimerTask, and so on:

Http://www.cnblogs.com/playing/archive/2011/03/24/1993583.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.