Full stack workshop training 13 --- Android --- message bus Mechanism

Source: Internet
Author: User

Full stack workshop training 13 --- Android --- message bus Mechanism

The blog post published yesterday tells about the content of network requests using asynchronous tasks in Android. At the end of the asynchronous task, Handler mechanism is used to notify the original Activity to update the interface. The netizen traburiss pointed out that, the onPostExecute of the asynchronous task is already in the UI thread, and Handler is used to execute the task until the next UI running cycle, which reduces the efficiency and violates the intention of the asynchronous task. Thanks to traburiss for his opinion, he is very correct. The reason why I use Handler is that I want to introduce the concept of message bus in Android Application Development and implement it based on Handler, it seems inappropriate to use this technology. Therefore, in this blog post, I will discuss the implementation part of the message bus together to avoid the problems raised by netizens.

First, we will introduce the message bus. The message bus refers to a system event. If you receive a message indicating that the user has successfully registered an asynchronous task, the system places the message on the message bus, application components that are interested in this message can subscribe to this message bus, so that when a message occurs, these components will be notified to complete the corresponding operation. The main advantage of introducing the message bus technology is the loose coupling between components. The message producer only needs to put the generated messages on the message bus without worrying about which component will use the message. The message consumer subscribes to the Message bus and can process the message when it occurs.

Let's first look at the implementation mechanism of the message bus. The Code is as follows:

 

Public class WkyMessageBus {public static void prepareEventBus () {messageBus = new HashMap
 
  
> (); // Add all message types to the HashMap on the message Bus
  
   
RegisterUserListeners = new HashMap
   
    
(); MessageBus. put (+ WkyConstants. Protocol, registerUserListeners);} public static void registerToMessageBus (int messageTypeId, String listenerName, Handler handler) {HashMap
    
     
Listeners = messageBus. get (+ messageTypeId); listeners. put (listenerName, handler);} public static void unregisterToMessageBus (int messageTypeId, String listenerName) {HashMap
     
      
Listeners = messageBus. get (+ messageTypeId); listeners. remove (listenerName);} public static void postMessage (Message msg) {HashMap
      
        Handlers = messageBus. get (+ msg. what); for (Handler handler: handlers. values () {handler. sendMessage (msg);} private static HashMap
       
         > MessageBus = null ;}
       
      
     
    
   
  
 


 

As shown in the code above, messageBus is used to represent the set of Message bus. The value of what of the Android Message object is changed to a string as the key, and its value is a list. The list element is Handler, the handler can send messages to the Activity to notify the Activity to perform related operations.

The Activity subscribes to the Message bus through the registerToMessageBus method. Call the unregisterToMessageBus method when the Activity is destroyed to log out of the message bus.

After the message producer generates the message, the message is published to the Message bus through postMessage.

When the Application starts, that is, the onCreate method of the Application Object of the Application, initializes the message bus.

 

WkyMessageBus.prepareEventBus();

 

As described in the previous article, when an asynchronous task ends, a message is sent to the Message bus:

 

/*** The method to be called when the asynchronous task ends. Update the notification page * [yan Tao 5.09.24] initial version */@ Overrideprotected void onPostExecute (String result) {JSONObject json = null; long userId = 0; try {json = new JSONObject (result); userId = json. getLong (userId);} catch (JSONException e) {// TODO Auto-generated catch blocke. printStackTrace ();} WkyRegisterLoginModel model = (WkyRegisterLoginModel) activity. getModel (); model. setUserId (userId); activity. onAsyncTaskResult (); Message msg = handler. obtainMessage (); msg. what = WkyConstants. MSG_WHAT_REGISTER_USER; Bundle params = new Bundle (); params. putString (WkyConstants. MSG_DATA_NAME, result); msg. setData (params); WkyMessageBus. postMessage (msg );}

The Code contains three parts. The first part is to update the data in the corresponding Model object, and the second part is to call the onAsyncTaskResult method of the heavy load of JysRegisterLoginActivity defined by the WkyActivity base class to update the interface, the third part is to generate a Message object and send it to the Message bus.

 

When JysRegisterLoginActivity is started, it is registered to the Message bus and canceled from the message bus upon destruction. The Code is as follows:

 

@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(com.weikangyun.wkylib.R.layout.activity_register_login);handler = new JysRegisterLoginHandler(this);messageBusListenerName = this.getClass().getCanonicalName() + System.currentTimeMillis();WkyMessageBus.registerToMessageBus(WkyConstants.MSG_WHAT_REGISTER_USER, messageBusListenerName, handler);getViewObjects();setupGuis();setupActionListeners();}@Overridepublic void onDestroy() {super.onDestroy();WkyMessageBus.unregisterToMessageBus(WkyConstants.MSG_WHAT_REGISTER_USER, messageBusListenerName);}

When the system generates a message, it will send a message to the Activity. The message processing is as follows:

 

 

Static protected class JysRegisterLoginHandler extends WkyRegisterLoginHandler {public JysRegisterLoginHandler (JysRegisterLoginActivity) {this. activity = activity;} public void handleMessage (Message msg) {super. handleMessage (msg); // handle the switch (msg. what) {case WkyConstants. MSG_WHAT_REGISTER_USER: activity. processRegisterUserResult (msg); break;} private JysRegisterLoginActivity activity = null ;}

In fact, there is still a problem left over, that is, the interface update problem at the end of the asynchronous message. The onAsyncTaskResult method of the asynchronous task callback function is defined in the WkyActivity class of the application, as shown below:

 

 

/*** After the asynchronous task is completed, this method is called back to perform the page update operation. Two functions are required: * 1. asynchronous task: In the onPostExecute function, place the result in the Model corresponding to the Activity * 2. activity: extracts data from the Model and updates the interface * [yan Tao 2015.12.04] initial version */public void onAsyncTaskResult (){}

In a specific Activity class, compile the interface to update the function. Note: In the onPostExecute method of the asynchronous task end method, we have updated the required data to the Model. Therefore, the onAsyncTaskResult method only needs to read the data from the Model for display.

 

Here, I want to add a question: why does our network request adopt asynchronous tasks instead of directly using thread technology? Is the asynchronous task encapsulation of interaction between threads and UI threads? In fact, this is only one aspect. Because behind asynchronous tasks is the thread pool managed by the system, the system will give a proper thread solution based on the number of CPU cores, current load, and other factors (start new threads or reuse old threads ). However, because the above information cannot be obtained, it is impossible to optimize the system level. Therefore, it is recommended that asynchronous tasks be used to solve the problem.

 

 

 

 

 

 

 



Related Article

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.