EventBus环境准备与使用

        EventBus使用解决组件间通讯的一个开源项目,我们平时在使用GreenDao的时候,首页上也会看到它的身影,可以点击查看,下面就来看看如何使用这个简单实用的开源项目。因为考虑到月底了,这个月才写了一篇博客,所以,我可能根据EventBus的文档介绍分为几篇来写(虽然每一部分都比较简单,哈哈)

参考文档             下一篇:EventBus事件处理线程模式

1,开源项目功能框架图与基本介绍

基本上每一篇介绍EventBus博客的文章都会贴上这张图,确实,它很生动的反映了EventBus的使用思想。就是发布事件(发布者)与订阅事件(订阅者),根据事件(对象)来区分,此外,它对发布的事件做了管理(是否是粘性事件),对订阅者的订阅方式(不同的线程模式)以及优先级(订阅的优先级)做了管理等等。那么,我们也知道,Android原本通过广播等方式也是可以实现组件间通信的,为什么要用这个开源项目了,那我们就来看看它有哪些优点:

原文内容:

  • Simple yet powerful: EventBus is a tiny library with an API that is super easy to learn. Nevertheless, your software architecture may great benefit by decoupling components: Subscribers do not have know about senders, when using events.
  • Battle tested: EventBus is one of the most used Android libraries: thousands of apps use EventBus including very popular ones. Over a billion app installs speak for themselves.
  • High Performance: Especially on Android, performance matters. EventBus was profiled and optimized a lot; probably making it the fastest solution of its kind.
  • Convenient Annotation based API (without sacrificing performance): Simply put the @Subscribe annotation to your subscriber methods. Because of a build time indexing of annotations, EventBus does not need to do annotation reflection during your app’s run time, which is very slow on Android.
  • Android main thread delivery: When interacting with the UI, EventBus can deliver events in the main thread regardless how an event was posted.
  • Background thread delivery: If your subscriber does long running tasks, EventBus can also use background threads to avoid UI blocking.
  • Event & Subscriber inheritance: In EventBus, the object oriented paradigm apply to event and subscriber classes. Let’s say event class A is the superclass of B. Posted events of type B will also be posted to subscribers interested in A. Similarly the inheritance of subscriber classes are considered.
  • Zero configuration: You can get started immediately using a default EventBus instance available from anywhere in your code.
  • Configurable: To tweak EventBus to your requirements, you can adjust its behavior using the builder pattern.

 

这里象征性的翻译一两个,因为翻译它们还有很多更好的方法:

  • 简单但强大:EventBus是一个非常简单且体积很小的开源库,然尔,你的项目将会因为它在组件解耦方面受益颇丰。订阅者在使用事件的时候不需要知道发布者是谁
  • 实际应用验证:EventBus是Android最流行的开源库之一,很多App都使用EventBus,有超过十亿的app安装量为其代言
  • 。。。。

 

1,使用步骤

       既然上面说的这么NB,那我们就来看看如何使用它,今天就简单介绍一下其最基本的使用

第一步:添加依赖

//方式1  gradle
implementation 'org.greenrobot:eventbus:3.1.1'   

//方式2  Maven
<dependency>
    <groupId>org.greenrobot</groupId>
    <artifactId>eventbus</artifactId>
    <version>3.1.1</version>
</dependency>     

//方式3  下载Jar包                                                

开源项目Github地址(有Jar下载地址)

第二步:定义事件

package com.hfut.operationeventbus;

/**
 * author:why
 * created on: 2019/2/22 16:01
 * description: event for test
 */
public class MSGEvent {
    String msgInfo;

    public MSGEvent(String msgInfo) {
        this.msgInfo = msgInfo;
    }

    public void setMsgInfo(String msgInfo) {
        this.msgInfo = msgInfo;
    }

    public String getMsgInfo() {
        return msgInfo;
    }
}

第三步:订阅事件并自定义事件处理逻辑

EventBus.getDefault().register(this);//订阅事件
  @Subscribe (threadMode = ThreadMode.MAIN)
    public void onMsgEvent(MSGEvent event) {
        Log.e(TAG, "我是订阅者,发布者发布的消息:"+event.getMsgInfo() );
    }

第四步:发布事件

 EventBus.getDefault().postSticky(new MSGEvent("我是最新的消息 " ));

3,演示示例

MainActivity.java

package com.hfut.operationeventbus;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author why
 * @date 2019-2-22 15:54:08
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivitytest";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.send_MsgEvent).setOnClickListener(this);
        EventBus.getDefault().register(this);//订阅消息
    }

    @Subscribe (threadMode = ThreadMode.MAIN)
    public void onMsgEvent(MSGEvent event) {
        Log.e(TAG, "我是订阅者,发布者发布的消息:"+event.getMsgInfo() );
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send_MsgEvent:            
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {              
                            EventBus.getDefault().postSticky(new MSGEvent("我是最新的消息 " +System.currentTimeMillis()));                  
                    }                 
                }, 1000,2000);
                break;
        }
    }
}

 

MSGEvent.java

package com.hfut.operationeventbus;

/**
 * author:why
 * created on: 2019/2/22 16:01
 * description: event for test
 */
public class MSGEvent {
    String msgInfo;

    public MSGEvent(String msgInfo) {
        this.msgInfo = msgInfo;
    }

    public void setMsgInfo(String msgInfo) {
        this.msgInfo = msgInfo;
    }

    public String getMsgInfo() {
        return msgInfo;
    }
}

日志结果:

这个是组件内部,下面是组件间的通信:

MainActivity.java代码:

package com.hfut.operationeventbus;

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

/**
 * @author why
 * @date 2019-2-22 15:54:08
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivitytest";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.send_MsgEvent).setOnClickListener(this);
        EventBus.getDefault().register(this);//订阅消息
    }

    @Subscribe (threadMode = ThreadMode.MAIN)
    public void onMsgEvent(MSGEvent event) {
        Log.e(TAG, "我是订阅者,发布者发布的消息:"+event.getMsgInfo() );
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send_MsgEvent:              
                        startActivity(new Intent(MainActivity.this,PublisherActivity.class));              
                break;
        }
    }
}

PublisherActivity.java代码:

package com.hfut.operationeventbus;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import org.greenrobot.eventbus.EventBus;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author why
 * @date 2019-2-27 16:37:11
 */
public class PublisherActivity extends AppCompatActivity {

    private static final String TAG = "PublisherActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publisher);
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                    EventBus.getDefault().postSticky(new MSGEvent(TAG +System.currentTimeMillis()));
            }
        }, 1000,2000);
    }
}

日志结果:

好了,到这里最基本的使用就介绍完了,使用真的很方便,后续还有很多其他用法介绍哟。

注:欢迎扫码关注

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值