EventBus3.0使用详解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014005316/article/details/74011094

EventBus简述

EventBus是一款针对Android 优化的发布/订阅总线。

EventBus优点:

EventBus简化了应用程序内各组件间、组件与后台线程间的通信。

开销小,代码更优雅,将发送者和接受者完全解耦

EventBus三要素

  • Event:事件,可以是任意类型的对象
  • Subscriber:事件订阅者,在EventBus3.0之前消息处理的方法只能限定于onEvent、onEventMainThread、onEventBackgroundThread和onEventAsync,他们代表了四种线程模型。在3.0之后,事件处理方法可以随便起名,但需要加一个注解@Subcribe,并且指定线程模型
  • Publisher:事件发布者,可以在任意线程发送事件。可以自己实例化EventBus对象,但一般使用 EventBus.getDefault()就可以了。直接调用EventBus的post(Object)方法发送事件

EventBus3.0的四种线程模型-ThreadMode

  • POSTING(默认) :如果使用事件处理函数指定了线程模型为POSTING,那么该事件在哪个线程中发布出来,事件处理函数就会在哪个线程中运行。也就是说发布事件和接受事件在同一个线程。在线程模型为POSTING的事件处理函数中尽量避免执行耗时操作,因为它会阻塞事件的传递
  • MAIN:事件的处理会在UI线程中执行。事件处理时间不能太长,可能会引起ANR
  • BACKGROUND:如果事件是在UI线程中发布出来的,那么该事件处理函数就会在子线程中运行,如果事件本来就是子线程中发布出来的,那么该事件处理函数直接在子线程中执行。在此事件处理函数中禁止进行UI更新操作。
  • ASYNC:无论事件在哪个线程发布,该事件处理函数都会在新建的子线程中执行,此事件处理函数中禁止进行UI更新操作。

添加依赖库

Android Studio 配置gradle:

compile 'org.greenrobot:eventbus:3.0.0'

定义消息类

package com.zhoujian.eventbus;

/**
 * Created by zhoujian on 2017/6/30.
 */

public class EventMessage
{

    private String name;

    private String country;

    private int age;

    private String description;


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "EventMessage{" +
                "name='" + name + '\'' +
                ", country='" + country + '\'' +
                ", age=" + age +
                ", description='" + description + '\'' +
                '}';
    }
}

注册和取消订阅事件

package com.zhoujian.eventbus;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivity extends AppCompatActivity {

    private Button mButton;
    private TextView mText;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //注册事件
        EventBus.getDefault().register(this);
        initView();
        clickEvent();

    }

    private void initView()
    {
        mButton = (Button) findViewById(R.id.sendEvent);
        mText = (TextView) findViewById(R.id.text);
    }

    private void clickEvent()
    {

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,SecondActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    //事件订阅者处理事件

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMotionEvent(EventMessage messageEvent){
        mText.setText(
                "姓名:"+messageEvent.getName()+"\n" +
                        "年龄:"+messageEvent.getAge() +"\n"+
                        "国家:"+messageEvent.getCountry() +"\n"+
                        "描述:"+messageEvent.getDescription());
    }
}

事件发布者发布事件

package com.zhoujian.eventbus;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by zhoujian on 2017/6/30.
 */

public class SecondActivity extends AppCompatActivity {

    private Button mButton;
    private EventMessage message;


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

        initMessage();



        mButton = (Button) findViewById(R.id.receiveEvent);

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(message);

                finish();
            }
        });
    }

    private void initMessage()
    {
        message = new EventMessage();

        message.setName("周建");

        message.setAge(28);

        message.setCountry("中国");

        message.setDescription("一名来自北京朝阳区的程序员");

    }
}

运行截图

这里写图片描述

猜你喜欢

转载自blog.csdn.net/u014005316/article/details/74011094