How the child thread updates the main thread-go

Source: Internet
Author: User

Android UI updates are available only in the UI thread, which is the main thread. In a child thread, if the UI update is to be made, the main thread is notified.

Several implementation methods are summarized below, welcome to add.

1, Runonuithread ()

A child thread holds the current activity reference (if it is an activity mactivity;), which can call Mactivity's Runonuithread (Runnable R) method.

2, Post () and Postdelay ()

A child thread can call the View object's post (Runnable R) or Postdelay (Runnable R) method if it holds a reference to the view to update the view

The handler object also has a post () method. In fact, in the Android source code, these post () methods are based on the following 3rd method: Handler + message to achieve.

3, Handler + message or Handler + Thread + message

When the main thread is established, it is looper by default and can handle Message Queuing.

Create a handler object on the main thread, and replicate its handlemessage () method to implement UI updates in the method.

Example:

private static final int msg_code = 1001;
Private Handler Mhandler = new Handler ()
{
@Override
public void Handlemessage (Message msg)

{

Receiving and processing messages

if (msg.what = = Msg_code)
{
UI Update
}
}
};

public void DoSomething ()
{
New Thread ()
{
@Override
public void Run ()

{

//child thread send message

message msg = Mhandler.obtainmessage (Msg_code);
msg.sendtotarget ();

}.start ();

}

4, broadcast

Send a broadcast in a child thread, receive a broadcast in the main thread, and update the UI

5, Asynctask

Asynctask can easily implement a new thread and return the results to the UI thread without the developer having to manually open a new thread or use handler for developers.

It should be noted that Asynctask is an abstract class whose three generic parameters have the following meanings:
asynctask<param, Progress, Result
param: Parameter type sent to the newly opened thread
result: The type of value returned to the UI thread after the thread task has finished processing.

onprogressupdate (Progress ... Progress), OnPostExecute (result result).
except, Doinbackground (Params ...) Method, the other three methods are running on the UI thread.

Customize a class to inherit asynctask and implement at least the Doinbackground () function 。 You can call Publishprogress (Progress ...) at any time during the execution of this function. Report on the progress of their implementation. Another method Onprogressupdate (Progress ... Progress) is triggered to update the progress of the task processing on some controls (such as ProgressBar) in the UI thread.

You can also wait for Doinbackground () to finish executing, and then update the UI control after entering the OnPostExecute () method.

Asynctask open tasks can be canceled at any time, in any thread (invoking the Cancel (Boolean mayinterruptifrunning) method of the custom Asyntask subclass)

Examples of use are:

If you remember correctly, this example should have been cut off from the official website before the summary.

public void OnClick (View v) {
New Downloadimagetask (). Execute ("Http://example.com/image.png");
}

Private class Downloadimagetask extends Asynctask<string, Void, bitmap> {
/** The system calls this to perform work in a worker thread and
     * delivers it the parameters given to Asynctask.execute () */
Span style= "WHITE-SPACE:PRE;" >   protected Bitmap doinbackground (String ... urls) {
       return loadimagefromnetwork (urls[0]);
   }
   
   /** The system calls this to perform work in the UI thread and delivers
& nbsp    * The result from Doinbackground () */
   protected void OnPostExecute (Bitmap result) {
        Mimageview.setimagebitmap (result);
   }
}

How a child thread updates the main thread-go

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.