Android Non-ui to UI Thread Communications (Part 3 of 5)

Source: Internet
Author: User

original:http://www.intertech.com/blog/android-non-ui-to-ui-thread-communications-part-3-of-5/

Continuing my series on Android non-ui thread-to-ui thread Communications, this post covers use of the Handler Framework t  o Facilitate the communications. See here for part 1 and part 2 of the series.

Non-ui threads is not a allowed to make updates to the UI. Trying to does too much work (as defined as not allowing the user to interact with the UI for more than 5 seconds) on the UI  Thread leads to ANR errors. In the first and the first of posts, I showed how to use an activity's Runonuithread () method and a view component ' s post () method to H Ave The Non-ui thread send a request through the underlying UI event message channel to the UI thread to execute a UI UPDA Te.

ANDROID ' S HANDLER FRAMEWORK

Android threads, in particular the UI thread, has a message queue.  Messages in the queue is processed by the thread in order of arrival.  In the that case of the UI thread, user events (like a button push) cause event messages to being placed in the queue.  As explained in the previous posts, the Runonuithread () and post () methods use this queue under the covers. However, you can use the message in the queue more directly.

Using the Handler Framework, you can create a message directly and put the message on the UI thread ' s queue from the non-u  I thread.  The framework also lets you build a message handler to listen for the message on the UI thread. Thus, the Handler framework can provide another means for the non-ui thread to communicate with the UI via the Framework p Ieces.

The Simpleapp REVIEW

As with the Last post, I provide the simple application (called Simple App) to demonstrate the use of the Handler Framewor  K for thread communications.  The app has both buttons to start/stop a Non-ui thread. The Non-ui thread ' s job is to simulate long running work by generating a random number, and the call the UI to has a TextView wid Get update the display of the random number, and then sleep for a number of seconds.

Now let's see how the Handler Framework can is used in this app to update the UI (the TextView) from the Non-ui thread.

OPTION 3–using the HANDLER FRAMEWORK

First, create a Handler in the UI thread to receive and react to new messages sent by the Non-ui thread. Here is the steps to create the Handler:

1. Create class that extends Android.os.Handler. For simplicity, I created the Handler subclass (called Handlerextension here) as a inner class to the application ' s Activ ity.

12345678910111213141516 private static class handlerextension extends Handler {      Private final weakreference<ShowSomethingActivity> currentactivity;   Public handlerextension(showsomethingactivity activity){ currentactivity = new weakreference<ShowSomethingActivity>( Activity);   }   @Override Public void handlemessage(message message){ showsomethingactivity activity = currentactivity. Get(); if (activity!= null){ activity. Updateresults(message. GetData(). GetString("result"));     }  }}

The code here is a little complex due to the static nature and WeakReference in the subclass. If you try to create a simple class This extends Handler, you'll find Eclipse and the SDK issues a compiler warning that The Handler class should be static or leaks might occur.

The issue is well explained in a StackOverflow post. While the code is a little more complex, the Post provides a great template example for creating the Handler subclass Without memory leaks.

2. Next, add a property to the Handler subclass instance in the Activity.

1 Handler resulthandler;

3. Then, from the activity ' s onCreate () method, create a instance of the Handler so it can start processing any Inco Ming messages from the Non-ui thread.

1 Resulthandler = new handlerextension(this);

Second, with the Handler subclass code in place, you can create a message from the NON-UI thread and publish it into the U I thread ' s message queue using the Handler subclass. Simply Create an instance of message and add data to the message to indicate to the Handler what UI changes should occur ( In this case, providing the random number, which needs to being displayed in the TextView widget).

123456789 private void publishprogress(int randnum) { Log. V(TAG, "reporting back from the Random number Thread");     string text = String. Format (getstring ( r. String. Service_msg ,randnum Bundle msgbundle = new bundle(); msgbundle. Putstring("Result", text); message msg = new message(); msg. SetData(msgbundle); resulthandler. SendMessage(msg);   }

The Simpleapp example code for demonstrating option #3 can is found here (in an Eclipse project ZIP file).

Considerations of OPTION 3–handler FRAMEWORK

The Runonuithread () and Post () methods examined in previous posts is really special hander Framework conveniences.  They use the event queue in the UI thread to perform their task.  Why is the Handler Framework directly as shown here?  The Using the Handler Framework directly is a bit more complex, but it allows you more control.  This is a generic the framework for thread Communication–any thread.  It also allows the non-ui thread to communicate without direct knowledge/ties to the activity or UI side components. The non-ui merely have to post a message to a handler.

WRAP up

In the final and the posts of this series, you'll see different Android infrastructure to perform the Non-ui to UI t upcoming  Hread communications–namely The use of broadcast receivers and Asynctask.  Stay tune for those posts. If you is looking for some Android training or consulting help, look no further than the sponsor of this blog Site:inte Rtech.



Read more:http://www.intertech.com/blog/android-non-ui-to-ui-thread-communications-part-3-of-5/#ixzz3MyuAnUgJ
Follow us: @IntertechInc on Twitter | Intertech on Facebook

Android Non-ui to UI Thread Communications (Part 3 of 5)

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.