Android Method for updating the UI by threads

Source: Internet
Author: User
Tags oracle developer

When an android program starts running, a process is started separately. By default, the activity or service (Service and activity are only two types of components provided by Android, and content provider and broadcast receiver) in this program will run in this process.
By default, an android program has only one process, but a process can have many threads.
Among so many threads, there is a thread, which is called the UI thread. The UI thread is created when the android program is running. It is the main thread in the process. It is mainly responsible for controlling the display, update, and control interaction of the UI interface. At the beginning of Android program creation, a process presents a single-threaded model, and all tasks are run in one thread. Therefore, we believe that the shorter the time required for every function executed by the UI thread, the better. Other time-consuming tasks (such as accessing the network, downloading data, and querying the database) should be executed by sub-threads to avoid blocking the main thread.
So how does the UI thread work with other threads? Common methods are:
A handler object of the main thread is generated. As a listener, The subthread can push messages to the Message quene of the main thread to trigger the handlermessage () function of the main thread, let the main thread know the sub-thread status and update the UI in the main thread.
For example, when the sub-thread status changes, We need to update the UI. If you update the UI directly in the Child thread, the following exception is thrown:
11-07 13:33:04. 393: Error/javabinder (1029): Android. View. viewroot $ calledfromwrongthreadexception: only the original thread that created a view hierarchy can touch its views.
It means that the UI cannot be updated in the Child thread. Therefore, we need to notify the main thread UI thread through the handler object to update the interface.
Create a handler to listen to message events as follows:
Private Final int update_ui = 1;
Private handler mhandler = new mainhandler ();
Private class mainhandler extends handler {
@ Override
Public void handlemessage (Message MSG ){
Switch (msg. What ){
Case update_ui :{
Log. I ("ttsdeamon", "update_ui ");
Showtextview. settext (edittext. gettext (). tostring ());
Showanimation ();
Break;
}
Default:
Break;
}
}
}
Or
Private handler mhandler = new handler (){
@ Override
Public void handlemessage (Message MSG ){
Switch (msg. What ){
Case update_ui :{
Log. I ("ttsdeamon", "update_ui ");
Showtextview. settext (edittext. gettext (). tostring ());
Showanimation ();
Break;
}
Default:
Break;
}
}
}
When the sub-thread status changes, a message is sent in the sub-thread to notify the updated UI.
Mhandler. sendemptymessagedelayed (update_ui, 0 );
In our program, many callback methods are sometimes not running in the main thread, so if the UI update fails in the callback method, you can also use the above method.
Article 2
Android UI design and background thread Interaction
Speaker ideasandroid I want to comment (0) font size: T | T
This article will discuss the thread model of Android applications and how to use threads to process time-consuming operations, instead of executing them in the main thread to ensure smooth operation of the user interface (UI.
Tags: Android UI
AD: register for "Oracle Global Conference · 2010 · Beijing" and "javaone and Oracle Developer Conference 2010"
Suo Yin
[Display]
In terms of Android UI design, we talked about the official tutorial on "android UI" design. This article will discuss the thread model of Android applications and how to use threads to process time-consuming operations, instead of executing them in the main thread to ensure smooth operation of the user interface (UI. This article also describes some APIs that interact with threads on the user interface (UI.
Ui User Interface thread
When an application starts, the system creates a main thread or UI thread for the application, which is responsible for distributing events to different components, including painting events. Complete the interaction between your application and the android UI component.
For example, when you touch a button on the screen, the UI thread will distribute the touch event to the component, change the status and add it to the event queue. The UI thread will distribute requests and notifications to each component, complete the action.
The performance of the single-thread model is very poor unless your application is quite simple, especially when all operations are executed in the main thread, for example, time-consuming operations such as accessing the network or database will cause the user interface to be locked, and all events will not be distributed, and the application will be like dead, more seriously, the system will pop up the "Application No response" dialog box when it exceeds 5 seconds.
If you want to see the effect, you can write a simple application and write thread in the onclicklistener of a button. sleep (2000), run the program and you will see that the button will remain in the pressed state for 2 seconds before the application returns to normal state. When this happens, you will feel that the application is quite slow.
In short, we need to ensure that the main thread (ui thread) is not locked. If there is a time-consuming operation, we need to put it in a separate background thread for execution.
The following is an example of downloading an image by clicking the button and displaying it on the Image view page:
Public void onclick (view v ){
New thread (New runnable (){
Public void run (){
Bitmap B = loadimagefromnetwork ();
Mimageview. setimagebitmap (B );
}
}). Start ();
}
At first, the above Code seems to be a good solution because it does not lock the user interface thread. Unfortunately, it violates the single-thread model of the user interface: the android User Interface toolkit is NOT thread-safe and can only be operated in the UI thread. In the code above, you call mimageview in a work thread. when setimagebitmap (B) is used, unexpected errors will occur, which are very difficult to track and debug.
Android provides several methods to access the UI thread from other threads. You may already be familiar with them. Below is a comprehensive list:
Activity. runonuithread (runnable)
View. Post (runnable)
View. postdelayed (runnable, long)
Handler
You can use any of these classes and methods to correct the previous code example:
Public void onclick (view v ){
New thread (New runnable (){
Public void run (){
Final bitmap B = loadimagefromnetwork ();
Mimageview. Post (New runnable (){
Public void run (){
Mimageview. setimagebitmap (B );
}
});
}
}). Start ();
}
Unfortunately, these classes and methods often make your code more complex and hard to read. What's worse, it needs to perform complex operation interface updates frequently.
To solve this problem, Android 1.5 and later versions provide an audit class called asynctask, which simplifies long-running tasks and requires interaction with the user interface.
A usertask class similar to asynctask can also be used in Android 1.0 and 1.1. It provides identical APIs. All you need to do is copy its source code to your application.
The goal of asynctask is to provide management services for your threads. The previous example can be easily rewritten using asynctask:
Public void onclick (view v ){
New downloadimagetask(cmd.exe cute ("http://www.ideasandroid.com/image.png ");
}
Private class downloadimagetask extends asynctask <string, void, bitmap> {
Protected bitmap doinbackground (string... URLs ){
Return loadimagefromnetwork (URLs [0]);
}
Protected void onpostexecute (Bitmap result ){
Mimageview. setimagebitmap (result );
}
}
As you can see, We must inherit the asynctask class to use it. It is very important that asynctask must be instantiated in the UI thread and can only be executed once.
The following describes how to use asynctask:
◆ You can specify three parameter types: Generic parameters, progress values (values returned during execution), and final values (values returned after execution ).
◆ This method doinbackground () automatically executes the working thread (background thread)
◆ Onpreexecute (), onpostexecute (), and onprogressupdate () are both called in the UI thread.
◆ The value () returned by doinbackground is sent to onpostexecute ()
◆ You can call publishprogress () when executing doinbackground () and then execute onprogressupdate () in the UI group ().
◆ You can cancel a task from any thread at any time
Whether or not you use asynctask, always remember the two rules of the single thread model:
1. Do not lock the user interface.
2. Ensure that only the components in the android User Interface toolkit are accessed in the UI thread.
Asynctask only makes it easier for you to do these tasks.

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.