EventBus communications expert and EventBus communications expert

Source: Internet
Author: User
Tags eventbus

EventBus communications expert and EventBus communications expert

1. EventBus Introduction

EventBus is a lightweight Android event publishing/subscription framework developed by greenrobot. It features simple code and is a design pattern of publishing and subscription (observer design pattern ).

EventBus can replace the traditional Android Intent, Handler, Broadcast or interface functions, and transmit data and execute methods between Fragment, Activity, and Service threads.

(Simple communication between threads may not show the advantages of EventBus, but there are many communication codes between processes, especially complicated data formats. EventBus can simplify communication)

2. Advantages of EventBus

1. Simplified communication between components

2. separated the event sender and receiver

3. Excellent Performance in Activity, Fragment and thread

4. Avoids complex and error-prone dependencies and declaration cycles.

5. Simpler code and better performance

6. faster and smaller (about 50 K jar package)

3. Principle of EventBus

1. At the underlying layer of EventBus, annotations and reflection are used to obtain the subscription method information (first, annotations are obtained. If annotations cannot be obtained, reflection is used). 1

2. The current subscriber is added to the subscriptionByEventType set of the Eventbus total event subscriber.

3. All subscribed events of the subscriber are added to the typeBySubscriber, so that the subscriber can be easily removed from the subscriber.

 

4. Procedure

 1. associated database compile 'org. greenrobot: eventbus: 3.0.0'

2. Set permissions (for Network Testing) <uses-permission android: name = "android. permission. INTERNET"/>

3. register EventBus. getDefault (). register (this );

4. Send the message EventBus. getDefault (). post ("this is a String statement ");

5. Accept Information

@ Subscribe () // nothing in it indicates the default public void getInfo (String a) {Log. e ("obtained String:", a); // String a is generally defined as a class. If it is simple, the basic String data format can be passed.} // public cannot be changed to private.

6. Remember to destroy registration upon exit

@Override    protected void onDestroy() {        super.onDestroy();        EventBus.getDefault().unregister(this);    }

 

 

5. CasesDemo click Download: http://www.cnblogs.com/wujiancheng

Test the communication between the main thread and the sub-thread (networking requests in the sub-thread, pop up the information sent from the sub-thread in the main thread), test the priority, and test the effect of Stickly)

 

1. Inter-thread Communication

Send message as EventBus. getDefault (). post (new XXX ("http://www.tngou.net/api/memo/comment"); // here XXX needs to correspond

The

@Subscribe(threadMode = ThreadMode.ASYNC)   public void TestHttp(XXX event){ ......}

 

 

 

 

 

EventBus. getDefault (). post ("I am a String ");

The receiving information is

@ Subscribe (threadMode = ThreadMode. ASYNC) public void TestHttp (String info) {...} // write a String type.

 

 

 

 

 

 

Send information url to subthread

@ Override public void onClick (View view) {// send EventBus. getDefault (). post (new HttpEvent ("http://www.tngou.net/api/memo/comment"); // here you need to write a parsed class, very simple with only two nodes}

The HttpEvent and HttpEvent2 code are the same, as follows:
public class HttpEvent {    private String msg;    public HttpEvent(String msg) {        this.msg = msg;    }    public String getMsg(){        return msg;    }}

 

Message sent by the subthread

// Here, XUtils is used to request the network. You can download the demo for details.
@ Subscribe (threadMode = ThreadMode. ASYNC) public void TestHttp (HttpEvent event) {String jsonData = event. getMsg (); // network request Log. e ("Thread name:", Thread. currentThread (). getName (); org. xutils. x. http (). get (new RequestParams (jsonData), new Callback. commonCallback <String> () {@ Override public void onSuccess (String result) {Log. e ("Networking request", "Networking successful =" + result); Gson gson = new Gson (); JsonData data = gson. fromJson (result, JsonData. class); // send the message EventBus. getDefault (). post (new HttpEvent2 (data. getMsg () + "-------" + data. isStatus ();} @ Override public void onError (Throwable ex, boolean isOnCallback) {Log. e ("network connection request", "network connection failed, please check network") ;}@ Override public void onCancelled (CancelledException cex) {}@ Override public void onFinished () {}});}

 

Accept and display information

@ Subscribe (threadMode = ThreadMode. MAIN) public void getMessage (HttpEvent2 event2) {Toast. makeText (this, event2.getMsg (), Toast. LENGTH_SHORT ). show (); Log. e ("Thread name:", Thread. currentThread (). getName ());}

 

The running effect is as follows:

The sub-thread requests the Internet. The main thread obtains information, as shown in the figure below.

 

 

 

EventBus3.0 four thread Modes

1. @ Subscribe (threadMode = ThreadMode. POSTING)

The thread where the subscriber executes and the event publisher is located is the same thread, which is also the default thread mode of EventBus.



2. @ Subscribe (threadMode = ThreadMode. MAIN)

Running in the main thread of Android cannot execute time-consuming tasks.



3. @ Subscribe (threadMode = ThreadMode. BACKGROUND)

Executed in the background thread. If the publisher publishes an event in the main thread, the subscriber re-starts a subthread to run it.

If the publisher publishes an event not in the main thread, the subscriber executes the task in the thread where the publisher is located.

 
4. @ Subscribe (threadMode = ThreadMode. ASYNC ),

Execute in an independent thread. no matter whether the publisher publishes an event in the main thread or child thread, the subscriber re-starts a thread to execute the task.

 

2. Test priority

The higher the priority (default priority is 0), the higher the priority, that is, the first execution. It must be tested in the same thread. The two threads have no comparable priority.


Send information
@ Override public void onClick (View view) {EventBus. getDefault (). post (new HttpEvent3 ("test priority "));}

Receive information

@ Subscribe (priority = 88) public void getPriority (HttpEvent3 event3) {Log. e ("priority = 88:", event3.getMsg () ;}@ Subscribe (priority = 10) public void getPriority2 (HttpEvent3 event3) {Log. e ("priority = 10:", event3.getMsg () ;}@ Subscribe (priority = 77) public void getPriority3 (HttpEvent3 event3) {Log. e ("priority = 77:", event3.getMsg (); EventBus. getDefault (). cancelEventDelivery (event3); // interrupt event transfer} @ Subscribe (priority = 99) public void getPriority4 (HttpEvent3 event3) {Log. e ("priority = 99:", event3.getMsg ());}

There are only three priorities, from large to small, for execution, because when 77 is interrupted, there is no priority = 10

 

3. test the effect of stickiness

Sticky EventBus type and sticky broadcast. messages are sent without registration, and the information is cached. When registering, you can receive previous messages.

 

// Test the viscosity EventBus. getDefault (). postSticky ("test Stickly"); // send it through postSticky // register EventBus. getDefault (). register (this );

Receive information

  @Subscribe(sticky = true)    public void getStickly(String a) {        Log.e("sticky = true:" ,a);    }    @Subscribe(sticky = false)    public void getStickly2(String a) {        Log.e("sticky = false:" ,a);    }

// Sticky = true to receive the message

 

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.