Using handler to implement message distribution mechanism in Android (iii)

Source: Internet
Author: User

In the second article, "How touse handler to implement message distribution mechanism in Android (i)", we talked about the main thread of the Looper is the Android system in the launch of the app, it has helped us to create a good, Assuming that you need to use handler in a sub-thread, we need to explicitly call Looper's prepare method and the loop method to create its unique looper for the child thread.

Detailed code such as the following:

Class Looperthread extends Thread {public          Handler Mhandler;          public void Run () {              looper.prepare ();              Mhandler = new Handler () {public                                  void Handlemessage (Message msg) {                      log.v ("Test", "Id of Looperthread:" + Thread . CurrentThread (). GetId ());                      ...                     }                  }              };              Looper.loop ();          }      }  

In fact, the Android SDK already provides such an implementation, a class called Handlerthread, which inherits threads, and calls the Looper.prepare () and Looper.loop () methods in its Run method, This creates a thread that already has a looper, as seen in the following code:

    @Override public    Void Run () {        Mtid = Process.mytid ();        Looper.prepare ();        Synchronized (this) {            mlooper = Looper.mylooper ();            Notifyall ();        }        Process.setthreadpriority (mpriority);        Onlooperprepared ();        Looper.loop ();        Mtid =-1;    }

The corresponding looper of the handler that we define in the main thread, or the main thread, is actually just the asynchronous processing in the main thread.

In daily development, when we need to use handler to implement business processing in sub-threads, we can use handlerintent to achieve our needs.

In general, we create a class that inherits Handlerthread, such as the following:

   public class Myhandlerthread extends Handlerthread {public        myhandlerthread (String name) {                        super (name);        }    }    protected void OnCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        LOG.V ("Test", "Id of Mainthread:" + thread.currentthread (). GetId ());        Myhandlerthread myhandlerthread = new Myhandlerthread ("Myhandlerthread");        Myhandlerthread.start ();        Handler Handler = new Handler (Myhandlerthread.getlooper (), new Callback () {            @Override public            Boolean Handlemessage (Message msg) {                log.v ("Test", "ID of Thread by Callback:" + thread.currentthread (). GetId ());                return false;            }        });        Handler.sendemptymessage (0);    }

In the example, a Myhandlerthead object is created, remembering that it is a thread, so it is necessary to call its Start method to let the thread run.

Next, you need to use one of the handler constructor handler (Looper, Callback) to assign Handlerthread to Looper, and then pass in the handler thread, is the Handler.callback interface implementation class, as seen in the code above.

Finally call the SendMessage method, the corresponding results such as the following:

10-28 17:24:50.438:v/test (31694): ID of mainthread:110-28 17:24:50.448:v/test (31694): ID of Thread by callback:91617

As can be seen, Handlemessage's processing logic is already running in another thread.

Normally, when we create a handlerthread, we also implement the Handler.callback interface, encapsulating the code logic we want to implement in this thread, making the code more readable, such as the following:

    public class Myhandlerthread extends Handlerthread implements callback{public        myhandlerthread (String name) {                        Super (name);        }        @Override Public        Boolean handlemessage (Message msg) {            log.v ("Test", "ID of the Thread by Callback:" + thread.current Thread (). GetId ());            return true;        }    }    protected void OnCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        LOG.V ("Test", "Id of Mainthread:" + thread.currentthread (). GetId ());        Myhandlerthread myhandlerthread = new Myhandlerthread ("Myhandlerthread");        Myhandlerthread.start ();        Handler Handler = new Handler (Myhandlerthread.getlooper (), myhandlerthread);        Handler.sendemptymessage (0);    }

When it comes to readability of code, sometimes we value the level of code or the modularity, coupling, and so on.

Different business logic, different functions, should be real in different modules, and modules and modules can communicate through a message, and such a message, we can use handler and handlerthread to achieve.

For example, a recent small demo of a browser, its class diagram such as the following:


In this, we use MessageDispatcher to store the handler of each module, such as the following:

   private static MessageDispatcher Mmsgdispatcher;          Private sparsearray

In different module implementations, we are able to invoke the Registerhandler method, register the handler of its object into MessageDispatcher, and then specify the corresponding target through the SendMessage method, Assuming that the corresponding target module is also messagedispatcher, it will be able to obtain its handler, and then use its handler to send the message and handle it.

For example, we send a message to Bookmarkmanager in bookmarkactivity, such as the following:

Mmessagedispatcher.sendmessage (Messageconstant.target_bookmark_mgr, Messageconstant.target_bookmark_activity,                        Messageconstant.msg_bookmark_get_all_dir, Sparsearray);

In Bookmarkmanager, when the handler receives the corresponding message, it will be processed accordingly, such as the following:

   Class Bookmarkhandlerthread extends Handlerthread implements callback{public        bookmarkhandlerthread (String name) {            super (name);                    }        @SuppressWarnings ("unchecked") public        Boolean handlemessage (Message msg) {                   switch (msg.what) {            case Messageconstant.msg_bookmark_get_all_dir:                 //do Something

In this way, we will separate the business logic and the data operation, and realize the function programming.

Although just a not very mature idea, but still want to share with you, in the design of the code architecture, can be based on functional, business requirements or infrastructure framework for layering, chunking, to achieve the loose coupling of code.

End.





Using handler to implement message distribution mechanism in Android (iii)

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.