Android project combat (thirteen): Talking about EventBus

Original: Android project combat (13): Talking about EventBus

Overview:

EventBus is a publish/subscribe event bus optimized for Android.

The main function is to replace Intent, Handler, BroadCast in Fragment, Activity, Service.

Messages are passed between threads. The advantages are less overhead, more elegant code, and decoupling of senders and receivers.

---------------------------------------------------------------------------------------

download:

Class library source code: https://github.com/greenrobot/EventBus

jar包:http://download.csdn.net/detail/yy1300326388/8727699

 

--------------------------------------------------------------------------------------- 

use:

build.gradle , if you don't need to download the class library or jar package in this way, you can import it in one sentence

    compile 'de.greenrobot:eventbus:2.4.0'

 

1. The use of EventBus, in simple terms, is 5 steps: create a class (specifically described below), register, send messages, receive messages, and deregister

See a demo:

Implementation function: There are two Activity, the first Activity jumps to the second Activity, the second Activity clicks the button to send a message, and the TextView in the first Activity displays the received message information

1. Write down the layout of the two Activity

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
 3     android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
 4     android:paddingRight="@dimen/activity_horizontal_margin"
 5     android:paddingTop="@dimen/activity_vertical_margin"
 6     android:paddingBottom="@dimen/activity_vertical_margin"
 7     android:orientation="vertical"
 8     tools:context=".MainActivity">
 9 
10     <TextView
11         android:layout_gravity="center"
12         android:id="@+id/show_msg"
13         android:text="@string/hello_world"
14         android:layout_width="wrap_content"
15         android:layout_height="wrap_content" />
16 
17     <Button
18         android:id="@+id/to_second_activity"
19         android:layout_gravity="center"
20         android:layout_width="wrap_content"
21         android:layout_height="wrap_content"
22         android:text="跳转第二个Activity"/>
23 
24 </LinearLayout>
activity_main
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical" android:layout_width="match_parent"
 4     android:layout_height="match_parent">
 5 
 6     <Button
 7         android:layout_width="wrap_content"
 8         android:layout_height= " wrap_content " 
9          android:text= " Send a message " 
10          android:id= " @+id/send_msg " />
 11  
12      < Button
 13          android:id= " @+id/btn_finish " 
14          android: text= " Destroy this Activity, return to the first Activity " 
15          android:layout_width= " wrap_content " 
16          android:layout_height= " wrap_content " />
17</LinearLayout>
activity_second

2. Create a class, the parameters of the construction method are not fixed, you can write it casually, and an empty class can also be used to transmit messages, depending on the specific requirements

package com.xqx.com.eventbusdemo;

public class MyMessage {
    private String string;
    public MyMessage(String string) {
        this.string = string;
    }
    public String getString() {
        return string;
    }
}

3. Register and unregister EventBus on the page where you receive the message (the first Activity), and get and process the message

Register in the onCreate() method

EventBus.getDefault().register(this);

Unregister in onDestroy() method

EventBus.getDefault().unregister(this);

Implement the method of obtaining and processing messages. Here, the onEventMainThread() method is used first, which means that the message is received and operated on the UI thread.

public void onEventMainThread(MyMessage event) {
        String msg = " onEventMainThread received message: " + event .getString();
        show_msg.setText(msg);
    }

Full code:

package com.xqx.com.eventbusdemo;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import de.greenrobot.event.EventBus;

public class MainActivity extends Activity {

    // Button, open the second Activity 
    private Button to_second_activity;
     // Text, display the received message 
    private TextView show_msg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView(R.layout.activity_main);

        to_second_activity = (Button) findViewById(R.id.to_second_activity);
        show_msg = (TextView) findViewById(R.id.show_msg);

        //注册
        EventBus.getDefault().register(this);

        // Click the button to enter the second Activity 
        to_second_activity.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,SecondActivity.class));
            }
        });


    }

    // Receive messages and process 
    public  void onEventMainThread(MyMessage event ) {
        String msg = " onEventMainThread received message: " + event .getString();
        show_msg.setText(msg);
    }

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

4. Send a message on the page where you want to send the message

Sending a message is very simple, the parameter is the class you wrote yourself 

EventBus.getDefault().post(new MyMessage("this is a message"));

Full code:

package com.xqx.com.eventbusdemo;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import de.greenrobot.event.EventBus;


public class SecondActivity extends Activity{

    private Button send_msg;
    private Button btn_finish;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView(R.layout.activity_second);

        send_msg = (Button) findViewById(R.id.send_msg);
        btn_finish = (Button) findViewById(R.id.btn_finish);

        send_msg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new MyMessage("this is a message"));
            }
        });

        btn_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }
}
SecondActivity.class

 

--------------------------------------------------------------------------------------- 

 Other knowledge of EventBus:

1. EventBus has four different message receiving and processing methods:

onEvent: 
Use onEvent, then which thread is the event published, onEvent will run in this thread, that is to say, the thread that publishes the event and the thread that receives the event are in the same thread. When using this method, time-consuming operations cannot be performed in the onEvent method, and event distribution delays may occur if time-consuming operations are performed.
onEventMainThread:
Use onEventMainThread, then no matter which thread the event is published in, onEventMainThread will be executed in the UI thread, and the received event will run in the UI thread, which is very useful in Android, because in Android only The new UI is updated in the UI thread, so time-consuming operations cannot be performed in the onEvnetMainThread method.
onEventBackgroundThread:
Use onEventBackgrondThread, then if the event is published in the UI thread, then onEventBackground will run in the sub-thread, if the event is originally published in the sub-thread, then the onEventBackground function is executed directly in the sub-thread.
onEventAsync:
Using onEventAsync, no matter which thread the event is published on, a new child thread will be created to execute onEventAsync.

 

2. If there are multiple places to send messages and there are multiple message processing functions, how to determine which message processing method handles which messages?

It depends on the parameters of the four message processing methods. The parameter for sending a message is a certain class, and the receiving class must also be this class, otherwise it will not be received. If there are multiple OnEvent() methods with the same parameters, these methods can all receive messages.

 

--------------------------------------------------------------------------------------- 

Summarize:

register (registration) will store the matching method (starting with onEvent) in the current class into a map, and post will search for the map according to the actual parameters and make a reflection call

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325033930&siteId=291194637