Android-non-ui-to-ui-thread-communications-part-4-of-5

Source: Internet
Author: User

In parts 1-3 of the This series, I has explored three different means for a Android non-ui thread to communicate user Interf Ace updates to the UI thread. The links below is to the series posts.

    • Part 1
    • Part 2
    • Part 3

In this fourth installment, I want to show you how to use a broadcasts and a broadcast receiver to provide non-ui to UI th Read communications.

BACKGROUND non-ui thread to UI thread COMMS

As background for those jumping into the middle of this series, non user interface (UI) threads is not allowed Updates to the ui.  for example, using a Non-ui thread to update a TextView ' s displayed text results in a calledfrom Wrongthreadexception.  however, 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 Android not responsive errors.  so you need to has Non-ui Threads perform Larger/bigger computing tasks, but need those threads to being able to communicate updates back to the UI th Read to perform display updates.

In the first three posts, I showed how to use an activity ' s Runonuithread () method, a View component ' s post () method, and The Android Handler Framework to has the Non-ui thread send a user interface update request back to the UI thread for dis  Play. Each of these past three options take advantage of the underlying UI event message channel to message the UI thread to per  form the user interface update. In this post, I show you a different means of providing the communications via broadcast intent that's acted on by a Broa Dcastreceiver on the UI thread.

Simple APP

A Simple application (called Simple App) would again be used to demonstrate the use of broadcast messages for thread commun  Ications.  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.

The application code for this-simple example are provided here .

OPTION 4–using A Broadcast

Broadcasts is Android Intents that indicate some action have occurred.  Some broadcasts is system broadcasts.  For example, one of the built on Android broadcast is and the battery is low. You can create your own custom broadcasts as well.

Broadcast receivers is in the application, that listen for broadcasts and take some action. Could, for example, build a broadcast receiver to listen for the battery getting low broadcast event in order to Infor  M the user that unsaved data should is saved quickly. Of course, you can also build a broadcast receiver to listen for your own custom application broadcasts.

So, a broadcast and broadcast receiver can is used to accomplish the NON-UI to UI thread communications. The Non-ui thread can publish a broadcast intent that a broadcast receiver associated to the UI thread uses to perform the UI Update.

Now, per the Android documentation on Broadcastreceivers, if your custom application broadcasts is not going to be used a   Cross applications, the should consider using a localbroadcastmanager to send a local broadcast versus a system broadcast.  A Localbroadcastmanager ' s intent broadcasts is not broadcast to other applications.  They is therefore a bit more efficient and secure than using a general broadcast message. You can read a prior blog post of mine to learn more about Localbroadcastmanager and local broadcasts.

Therefore, given the fact, the Non-ui to UI thread communication was local to your application, I would recommend (and would show below) using the Localbroadcastmanager to perform the thread communications.

Publishing the broadcast

First, from the Non-ui thread, create a Intent that provides the necessary information to the UI thread about the user in  Terface updates that is required. In this example, the Non-ui thread simply provides the new random number is generated as extra data (under the key O  F "Result") in the Intent. Then use a instance of Android ' s Localbroadcastmanager to send the local broadcast.

123 Intent Intent = new Intent("com.intertech.random.generation"); Intent. PutExtra("Result", text); Localbroadcastmanager. GetInstance(showsomethingactivity. This). Sendbroadcast(intent);

SET A Broadcast RECEIVER LISTENING

On the UI thread, you need to create a instance of Broadcastreceiver to listen for updates coming from the Non-ui thread. In this simple application, I created a anonymous broadcastreceiver instance from within the Createbroadcastrecevier () Method which is called from the OnCreate () method of the application ' s main activity.

12345678 private broadcastreceiver createbroadcastreceiver() { return new broadcastreceiver() { @Override Public void onreceive(context context, Intent Intent) c14> { updateresults(intent. Getstringextra("result"));     }  };}

The Updateresults () method of the broadcast receiver gets the TextView and updates the string with what's in the Broadcas T ' s extra data at "result".

Once the broadcast receiver is created in onCreate (), use a localbroadcastmanager to register the UI thread for the BROADC ASTs sent by the Non-ui thread, specifically those with the string action of "com.intertech.random.generation");

123456789 @Overrideprotected void onCreate(Bundle savedinstancestate) {   .. . resultreceiver = createbroadcastreceiver(); Localbroadcastmanager. GetInstance(this). Registerreceiver(resultreceiver, new intentfilter(" Com.intertech.random.generation "));   .. .}

Now, once the NON-UI thread publishes it local broadcast, the broadcast receiver listening for the message gets the Inten T and takes on the responsibility of updating the UI on the UI thread.

As a last bit of housekeeping, make sure to unregister the broadcast receiver when the communication between Non-ui and UI  Threads is no longer needed. In this example, I unregister the broadcastreceiver in the OnDestroy () method of the main activity.

1234567 @Overrideprotected void OnDestroy() { if (resultreceiver! = null) { Localbroadcastmanager. GetInstance(this). Unregisterreceiver(resultreceiver);   } Super. OnDestroy(); }

Considerations of OPTION 4–broadcasts

The broadcast option isn't reliant on the message event queue. Instead it relies on a different Android set of components;  namely the Intent and Intent listener called a broadcast receiver.  This sub-framework has pluses and minuses. There is no convenience methods as provided through methods like post () and Runonuithread () using the thread ' s event queu  E. Some consider working with Intents, broadcastreceivers (and Localbroadcastmanager) a bit more complex.  However, the broadcast intent can conveniently carry quite a bit of data to the UI thread from the Non-ui thread.  Also importantly, the NON-UI thread and UI thread does not have a to share any component knowledge.  The Non-ui thread is a quite decoupled from the UI thread. The only information gkfx by the threads is the name of the intent action.

WRAP up

Just One more post in the this series. In that post, I'll show you how to use an asynctask's for does long running work on a separate non-ui thread, while still be ing able to push changes to the UI via special UI thread methods.

Please connect with the Intertech if you or your organization could use the Help on your Android/mobile project.



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

Android-non-ui-to-ui-thread-communications-part-4-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.