EventBus 加强学习深入了解

Stella981
• 阅读 340

一、概述

前一篇给大家装简单演示了EventBus的onEventMainThread()函数的接收,其实EventBus还有另外有个不同的函数,他们分别是:

1、onEvent
2、onEventMainThread
3、onEventBackgroundThread
4、onEventAsync

这四种订阅函数都是使用onEvent开头的,它们的功能稍有不同,在介绍不同之前先介绍两个概念:
告知观察者事件发生时通过EventBus.post函数实现,这个过程叫做事件的发布,观察者被告知事件发生叫做事件的接收,是通过下面的订阅函数实现的。

**onEvent:如果使用onEvent作为订阅函数,那么该事件在哪个线程发布出来的,onEvent就会在这个线程中运行,也就是说发布事件和接收事件线程在同一个线程。使用这个方法时,在onEvent方法中不能执行耗时操作,如果执行耗时操作容易导致事件分发延迟。
onEventMainThread
:**如果使用onEventMainThread作为订阅函数,那么不论事件是在哪个线程中发布出来的,onEventMainThread都会在UI线程中执行,接收事件就会在UI线程中运行,这个在Android中是非常有用的,因为在Android中只能在UI线程中跟新UI,所以在onEvnetMainThread方法中是不能执行耗时操作的。
**onEventBackground:**如果使用onEventBackgrond作为订阅函数,那么如果事件是在UI线程中发布出来的,那么onEventBackground就会在子线程中运行,如果事件本来就是子线程中发布出来的,那么onEventBackground函数直接在该子线程中执行。
onEventAsync:使用这个函数作为订阅函数,那么无论事件在哪个线程发布,都会创建新的子线程在执行onEventAsync.  

二、实战

1、解析

上面列出的这四个函数,关键问题在于,我们怎么指定调用哪个函数呢?

我们先研究一下,上一篇中是怎么调用的onEventMainThread函数,除了在接收端注册与反注册以后,关键问题在于新建的一个类:

新建一个类:

package com.harvic.other;

public class FirstEvent {

private String mMsg;
public FirstEvent(String msg) {
    // TODO Auto-generated constructor stub
    mMsg = msg;
}
public String getMsg(){
    return mMsg;
}

}

发送时:

EventBus.getDefault().post(new FirstEvent("FirstEvent btn clicked"));

接收时:

public void onEventMainThread(FirstEvent event) {

    ……
}

发现什么问题了没?

没错,发送时发送的是这个类的实例,接收时参数就是这个类实例。

所以!!!!!!当发过来一个消息的时候,EventBus怎么知道要调哪个函数呢,就看哪个函数传进去的参数是这个类的实例,哪个是就调哪个。那如果有两个是呢,那两个都会被调用!!!!

为了证明这个问题,下面写个例子,先看下效果

2、实例

先看看我们要实现的效果:

这次我们在上一篇的基础上,新建三个类:FirstEvent、SecondEvent、ThirdEvent,在第二个Activity中发送请求,在MainActivity中接收这三个类的实例,接收时的代码为:

public void onEventMainThread(FirstEvent event) {

Log.d("harvic", "onEventMainThread收到了消息:" + event.getMsg());

}

public void onEventMainThread(SecondEvent event) {

Log.d("harvic", "onEventMainThread收到了消息:" + event.getMsg());

}

public void onEvent(ThirdEvent event) { Log.d("harvic", "OnEvent收到了消息:" + event.getMsg()); }

使用两个onEventMainThread分别接收FirstEvent实例的消息和SecondEvent实例的消息,使用onEvent接收ThirdEvent实例的消息。界面操作及结果如下:

EventBus 加强学习深入了解

Log输出结果:

EventBus 加强学习深入了解

可以看到,在发送FirstEvent时,在MainActiviy中虽然有三个函数,但只有第一个onEventMainThread函数的接收参数是FirstEvent,所以会传到它这来接收。所以这里识别调用EventBus中四个函数中哪个函数,是通过参数中的实例来决定的。

因为我们是在上一篇例子的基础上完成的,所以这里的代码就不详细写了,只写改动的部分。

1、三个类

package com.harvic.other;

public class FirstEvent {

private String mMsg;
public FirstEvent(String msg) {
    // TODO Auto-generated constructor stub
    mMsg = msg;
}
public String getMsg(){
    return mMsg;
}

}

package com.harvic.other;

public class SecondEvent{

private String mMsg;
public SecondEvent(String msg) {
    // TODO Auto-generated constructor stub
    mMsg = "MainEvent:"+msg;
}
public String getMsg(){
    return mMsg;
}

}

package com.harvic.other;

public class ThirdEvent {

private String mMsg;
public ThirdEvent(String msg) {
    // TODO Auto-generated constructor stub
    mMsg = msg;
}
public String getMsg(){
    return mMsg;
}

}

2、发送

然后在SecondActivity中新建三个按钮,分别发送不同的类的实例,代码如下:

package com.harvic.tryeventbus2;

import com.harvic.other.FirstEvent; import com.harvic.other.SecondEvent; import com.harvic.other.ThirdEvent;

import de.greenrobot.event.EventBus; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button;

public class SecondActivity extends Activity { private Button btn_FirstEvent, btn_SecondEvent, btn_ThirdEvent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity\_second);
    btn\_FirstEvent = (Button) findViewById(R.id.btn\_first\_event);
    btn\_SecondEvent = (Button) findViewById(R.id.btn\_second\_event);
    btn\_ThirdEvent = (Button) findViewById(R.id.btn\_third\_event);

    btn\_FirstEvent.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            EventBus.getDefault().post(
                    new FirstEvent("FirstEvent btn clicked"));
        }
    });
    
    btn\_SecondEvent.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            EventBus.getDefault().post(
                    new SecondEvent("SecondEvent btn clicked"));
        }
    });

    btn\_ThirdEvent.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            EventBus.getDefault().post(
                    new ThirdEvent("ThirdEvent btn clicked"));

        }
    });

}

}

3、接收

在MainActivity中,除了注册与注册,我们利用onEventMainThread(FirstEvent event)来接收来自FirstEvent的消息,使用onEventMainThread(SecondEvent event)接收来自SecondEvent 实例的消息,使用onEvent(ThirdEvent event) 来接收ThirdEvent 实例的消息。

package com.harvic.tryeventbus2;

import com.harvic.other.FirstEvent; import com.harvic.other.SecondEvent; import com.harvic.other.ThirdEvent;

import de.greenrobot.event.EventBus; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView;

public class MainActivity extends Activity {

Button btn;
TextView tv;
EventBus eventBus;

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

    EventBus.getDefault().register(this);

    btn = (Button) findViewById(R.id.btn\_try);

    btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(getApplicationContext(),
                    SecondActivity.class);
            startActivity(intent);
        }
    });
}

public void onEventMainThread(FirstEvent event) {

    Log.d("harvic", "onEventMainThread收到了消息:" + event.getMsg());
}

public void onEventMainThread(SecondEvent event) {

    Log.d("harvic", "onEventMainThread收到了消息:" + event.getMsg());
}

public void onEvent(ThirdEvent event) {
    Log.d("harvic", "OnEvent收到了消息:" + event.getMsg());
}

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    EventBus.getDefault().unregister(this);
}

}

在MainActivity中接收时,我们在接收SecondEvent时,在上面onEventMainThread基础上另加一个onEventBackgroundThread和onEventAsync,即下面的代码:

//SecondEvent接收函数一 public void onEventMainThread(SecondEvent event) {

    Log.d("harvic", "onEventMainThread收到了消息:" + event.getMsg());
}
//SecondEvent接收函数二
public void onEventBackgroundThread(SecondEvent event){
    Log.d("harvic", "onEventBackground收到了消息:" + event.getMsg());
}
//SecondEvent接收函数三
public void onEventAsync(SecondEvent event){
    Log.d("harvic", "onEventAsync收到了消息:" + event.getMsg());
}

完整的代码在这里:

package com.harvic.tryeventbus2;

import com.harvic.other.FirstEvent; import com.harvic.other.SecondEvent; import com.harvic.other.ThirdEvent;

import de.greenrobot.event.EventBus; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView;

public class MainActivity extends Activity {

Button btn;
TextView tv;
EventBus eventBus;

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

    EventBus.getDefault().register(this);

    btn = (Button) findViewById(R.id.btn\_try);

    btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(getApplicationContext(),
                    SecondActivity.class);
            startActivity(intent);
        }
    });
}

public void onEventMainThread(FirstEvent event) {

    Log.d("harvic", "onEventMainThread收到了消息:" + event.getMsg());
}

//SecondEvent接收函数一
public void onEventMainThread(SecondEvent event) {

    Log.d("harvic", "onEventMainThread收到了消息:" + event.getMsg());
}
//SecondEvent接收函数二
public void onEventBackgroundThread(SecondEvent event){
    Log.d("harvic", "onEventBackground收到了消息:" + event.getMsg());
}
//SecondEvent接收函数三
public void onEventAsync(SecondEvent event){
    Log.d("harvic", "onEventAsync收到了消息:" + event.getMsg());
}

public void onEvent(ThirdEvent event) {
    Log.d("harvic", "OnEvent收到了消息:" + event.getMsg());
}

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    EventBus.getDefault().unregister(this);
}

}

经过上面的分析,当发送SecondEvent实例的消息过来的时候,这三个函数会同时接收到并各自执行,所以当点击Second Event这个button的时候,会出现下面的结果:

EventBus 加强学习深入了解  

参考文章:

《Android解耦库EventBus的使用和源码分析》:http://blog.csdn.net/yuanzeyao/article/details/38174537

《EventBus的使用初试》:http://blog.csdn.net/pp_hdsny/article/details/14523561

《EventBusExplained 》:https://code.google.com/p/guava-libraries/wiki/EventBusExplained

《Google Guava EventBus实例与分析》

项目实例代码:

    https://github.com/wangzhiyuan888/EventBusDemo

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Stella981 Stella981
2年前
HIVE 时间操作函数
日期函数UNIX时间戳转日期函数: from\_unixtime语法:   from\_unixtime(bigint unixtime\, string format\)返回值: string说明: 转化UNIX时间戳(从19700101 00:00:00 UTC到指定时间的秒数)到当前时区的时间格式举例:hive   selec
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这