Android-EventBus-3.0.0 use

First paste the acquisition method:
  • Direct git clone down: git clone https://github.com/greenrobot/EventBus.git
  • Download it from the github website. https://github.com/greenrobot/EventBus These two methods have to manually put the jar package into the libs directory of the project, and then add dependencies
  • Add code to build.gradle in the project directory of androidstudio: compile 'org.greenrobot:eventbus:3.0.0' will be automatically downloaded to the project's External Libraries (this code is under the dependencies node)
  • I downloaded it, click to download http://download.csdn.net/detail/chenyannan0617/9509229

Brief introduction:

The open source framework EventBus is used in applications when you want to notify other components that something happens. Its main function is to replace Intent, Handler, and BroadCast to pass messages between Fragment, Activity, Service, and thread. The advantage is that the overhead is small, the code is concise, and the code is decoupled.

Post an official picture:

I think the picture describes one thing, the publisher publisher sends events through the post method, and the subscriber subscribers get the

key method:
  • EventBus.getDefault().register(this);//Subscribe to events
  • EventBus.getDefault().post(object);//Post events
  • EventBus.getDefault().unregister(this);//Unsubscribe

There are four forms on the event receiver (that is, four thread modes):
  • ThreadMode.POSTING: If the subscriber specifies this thread mode when using the event processing function, then which thread is the event published on, then the processing function will be executed in this thread, that is to say, the event is published and received. are in the same thread. Try to avoid time-consuming operations in this thread mode, because it will block the delivery of events, which is likely to cause ANR
  • ThreadMode.ASYNC: This thread mode means that no matter which thread the event is posted on, the event handler will be executed in the newly created child thread. UI operations cannot be performed in this event handler.
  • ThreadMode.BACKGROUND: This thread mode means that if the event is posted in the UI thread, then the event handler will be executed in the child thread; if the event is posted in the child thread, it is still in this thread processed in the thread. UI operations cannot be updated in this mode
  • ThreadMode.MAIN: If the thread mode is MAIN, no matter what thread the event is sent on, the event handler will be executed in the UI thread and can be used to update the UI, but be careful not to do time-consuming operations.

For example, the code above is
simple: there are two interfaces, ActivityA and ActivityB. After jumping from the ActivityA interface to the ActivityB interface, ActivityB sends a message to ActivityA, and ActivityA receives the message and displays it on the interface.
Implementation method: A Register in B, receive the subscribed event, cancel the registration; post event in B; first look at the effect

Code : A activity
public class MainActivity extends Activity {  
  
    Button   btn;  
    private TextView mText;  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate (savedInstanceState);  
        setContentView(R.layout.activity_main);  
//Register EventBus  
        EventBus.getDefault().register(this);  
        mText = (TextView) findViewById(R.id.text);  
        btn = (Button) findViewById(R.id.btn_try);  
  
        btn.setOnClickListener(new View.OnClickListener() {  
  
            @Override  
            public void onClick(View v) {  
                Intent intent = new Intent(getApplicationContext(), SecondActivity.class);  
                startActivity(intent);  
            }  
        });  
    }  
//Receive subscribed events  
    @Subscribe(threadMode = ThreadMode.POSTING)  
    public void getdate(String event) {  
        mText.setText(event);  
    }  
// unregister  
    @Override  
    protected void onDestroy() {  
        super.onDestroy ();  
        EventBus.getDefault().unregister(this);  
    }  
}

B activity
public class SecondActivity extends Activity {  
    private Button btn_FirstEvent;  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate (savedInstanceState);  
        setContentView(R.layout.activity_second);  
        btn_FirstEvent = (Button) findViewById(R.id.btn_first_event);  
        btn_FirstEvent.setOnClickListener(new View.OnClickListener() {  
  
            @Override  
            public void onClick(View v) {  
// send event  
                EventBus.getDefault().post("The second interface, POSITING sent back");  
                Toast.makeText(getApplicationContext(), "sent back", Toast.LENGTH_SHORT).show();  
            }  
        });  
    }  
}

Another attribute usage: EventBus can also receive the last event sent when it is not registered; if the event is sent without registration, if you register after sending it three times, you can now get the last event sent. The only code that works is sticky = true; note that when sending the event, it is not post but postSticky; if this code is not added, there is no such effect. Let's take a look at the picture first.

Paste the code:
Main Activity
public class MainActivity extends Activity {  
  
    int index = 1;  
    int count = 1;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate (savedInstanceState);  
        setContentView(R.layout.activity_sticky_mode);  
        findViewById(R.id.post).setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View v) {  
                Toast.makeText(getApplicationContext(), "发送弟"+count++ +"次", Toast.LENGTH_SHORT).show();  
                EventBus.getDefault().postSticky(new MessageEvent("Send event brother: " + index++ +" times"));  
            }  
        });  
        findViewById(R.id.regist).setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View v) {  
                EventBus.getDefault().register(MainActivity.this);  
            }  
        });  
  
        findViewById(R.id.unregist).setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View v) {  
                EventBus.getDefault().unregister(MainActivity.this);  
            }  
        });  
  
    }  
  
    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)  
    public void postThread(MessageEvent messageEvent) {  
        Log.e("PostThread", messageEvent.getMessage()+Thread.currentThread().getName());  
    }  
  
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)  
    public void mainThread(MessageEvent messageEvent) {  
        Log.e("MainThread", messageEvent.getMessage()+Thread.currentThread().getName());  
    }  
  
    @Subscribe(threadMode = ThreadMode.BACKGROUND, sticky = true)  
    public void backgroundThread(MessageEvent messageEvent) {  
        Log.e("BackgroundThread", messageEvent.getMessage()+Thread.currentThread().getName());  
    }  
  
    @Subscribe(threadMode = ThreadMode.ASYNC, sticky = true)  
    public void async(MessageEvent messageEvent) {  
        Log.e("Async", messageEvent.getMessage()+Thread.currentThread().getName());  
    }  
  
}

xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
              android:layout_width="match_parent"  
              android:layout_height="match_parent"  
              android:orientation="vertical">  
        <Button  
            android:id="@+id/post"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:text="Send event"/>  
  
        <Button  
            android:id="@+id/regist"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:text="Register"/>  
  
        <Button  
            android:id="@+id/unregist"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:text="Unregister"/>  
  
    </LinearLayout>

MessageEvent class
public class MessageEvent {  
  
    private String message;  
  
    public MessageEvent(String message) {  
        this.message = message;  
    }  
  
    public String getMessage() {  
        return message;  
    }  
  
    public void setMessage(String message) {  
        this.message = message;  
    }  
}

It can also be seen from the figure and code that the rules of the four threading modes. From what thread to send the event, to what thread to get the event.

In the second example, the events are all sent from the main thread. The received thread modes are Main and post, and they are also received in the main thread. In the other two modes, they are received in the child thread.

Welcome to the group discussion: 104286694

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326612982&siteId=291194637