Android methods for threading Update UI

Source: Internet
Author: User

Android methods for threading update UIWhen an Android program starts running, a process is started separately. By default, all activity or service (service and activity) in this program is only two of the components that Android provides, in addition to content provider and broadcast Receiver) will run in this process.
An Android program has only one process by default, but a process can have a number of thread.
Among so many thread, there is a thread, which we call the UI Thread. The UI thread is created when the Android program is running, and is the main thread of a process that is responsible for controlling the display, update, and control interaction of the UI interface. At the beginning of the Android program, a process presented a single-threaded model, with all tasks running in one thread. Therefore, we think that every function that the UI thread executes should take as short a time as possible. Other more time-consuming work (access to the network, download data, query database, etc.), should be left to the sub-thread to do so as not to block the main thread.
So how does the UI thread work with the other thread? Common methods are:
The handler object, which is the main thread, is created as listener to allow the child thread to push the message into the main thread's message quene in order to trigger the Handlermessage () function of the main thread, let the main thread know the state of the child threads, and update the UI on the main thread.
For example, when the state of a child thread changes, we need to update the UI. If the UI is updated directly in a child thread, the following exception is usually 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 it views.
This means that the UI cannot be updated in the child thread. To do this, we need to update the interface by handler objects, notifying the main thread UI thread.
As follows, first create a handler to listen for the message event:
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 state of the child thread changes, a message is emitted in the child thread informing the update UI.
Mhandler.sendemptymessagedelayed (update_ui, 0);
In our program, many callback methods are sometimes not run in the main thread, so if you update the UI in the callback method fails, you can also use the above method.
Second article
Android UI design interacts with background threads   This article discusses the threading model of Android applications and how to use threads to handle lengthy operations, rather than executing them in the main thread, ensuring a smooth user interface (UI).
    In the context of Android UI design, we've talked about the official Android UI design tutorial. This article discusses the threading model of Android applications and how to use threads to handle lengthy operations, rather than executing them in the main thread, ensuring a smooth user interface (UI). This article also explains some of the APIs in the user interface (UI) that interact with threads.
UI user Interface Threads
When the application starts, a main thread (main) or UI thread is created for the application, and it is responsible for distributing events to different components, including painting events. Complete your application to interact with the Android UI component.
For example, when you touch a button on the screen, the UI thread distributes the touch events to the component, changes the state and joins the event queue, and the UI thread distributes the requests and notifications to each component to complete the corresponding action.
The performance of a single-threaded model is very poor, unless your application is fairly simple, especially when all operations are performed in the main thread, such as time-consuming operations such as accessing the network or database, which will cause the user interface to be locked, all events cannot be distributed, the application is dead, and, more seriously, when more than 5 seconds The "Application is unresponsive" dialog box pops up.
If you want to see what effect, you can write a simple application, write Thread.Sleep (2000) in a button's Onclicklistener, run the program and you will see that the button will remain pressed for 2 seconds before the application returns to its normal state. When this happens, you will feel that the application reflects quite slowly.
In short, we need to ensure that the main thread (UI thread) is not locked, and if there is a time-consuming operation, we need to put it into a separate background thread to execute.
Below is an example of a click button to download an image while displaying the ImageView on the interface:
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 user interface single-threaded model: The Android User Interface Toolkit is not thread-safe, it can only be manipulated in the UI thread, and in the code above, when you call Mimageview.setimagebitmap (b) in a worker thread, Unexpected errors will occur, which are very difficult to track and debug.
Android provides several ways to access the UI thread from other threads. You may already be familiar with them, here is a more 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 preceding 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 also tend to make your code more complex and more difficult to read. To make things worse, it requires frequent and complex interface updates.
To solve this problem, the 1.5 and later versions of the Android platform provide a practical class called Asynctask, which simplifies long-running tasks and requires interaction with the user interface.
A class usertask like Asynctask is also available for Android 1.0 and 1.1, which provides the exact same API, all you need to do is copy its source code into your application.
The goal of Asynctask is to provide management services for your thread, and our previous example can be easily rewritten with Asynctask:
public void OnClick (View v) {
New Downloadimagetask (). Execute ("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 have to use it by inheriting the Asynctask class, and it's important to note that Asynctask must instantiate it in the UI thread and execute it only once.
Here is a brief use of Asynctask:
You can specify three parameter types, generic parameters, progress values (values returned during execution), and final values (the returned values are executed).
The method Doinbackground () automatically executes the worker thread (background thread)
OnPreExecute (), OnPostExecute (), and onprogressupdate () are all called in the UI thread
The value returned by Doinbackground () is sent to OnPostExecute ()
You can call Publishprogress () when you execute Doinbackground () and then execute Onprogressupdate () in the UI group.
You can cancel a task at any time from any thread
Regardless of whether you use Asynctask, always keep in mind the two rules of the single threading model:
1, do not lock the user interface.
2. Ensure that the components in the Android User Interface Toolkit are accessed only in the UI thread.
Asynctask just can make it easier for you to do these things.

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.