EventBus的原理及使用

EventBus是一个类似观察者模式功能的开源库
EventBus的使用步骤
1.定义一个事件Event
2.定义一个观察者Subscriber,并将该观察者注册到EventBus中
3.EventBus将事件分发出去,并通知观察者该事件已经发生
4.响应该事件
5.使用完后EventBs反注册观察者

是通过EventBus的post()方法告知观察者事件发生。告知观察者事件发生的过程叫做事件的发布,观察者被告知事件发生叫做事件的接收,
是通过下面四个订阅函数实现的。
onEvent()
onEventMainThread()
onEventBackground()
onEventAsync()
四个方法的不同
onEvent():
如果使用onEvent()作为订阅函数,那么该事件在哪个线程中发布出来,onEvent()函数就在这个线程中运行,
也就是说发布事件的线程和接收事件的线程实在同一个线程.
注意:使用该方法时,在onEvent方法中不能执行耗时的操作,如果执行耗时的操作容易导致事件分发延迟.
onEventMainThread():
如果使用onEventMainThread作为订阅函数,那么不管事件是在哪个线程中发布,onEventMainThread方法都会在UI线程中执行,
接收事件就会在UI线程中执行,这个在Android中是非常常用的,因为在Android中只能在Ui线程中更新UI,所以onEventMainThread方法中是不能执行耗时操作的.
onEventBackground():
如果使用onEventBackground作为订阅函数,那么如果事件是从UI线程中发布出来的,onEventBackground就会在子线程中执行,
如果事件是从子线程中发布出来的,onEventBackground就会在该子线程中执行.
onEventAsync():使用onEventAsync作为订阅函数,那么不管事件是在哪个线程中发布,都会创建新的子线程执行onEventAsync. 

EventBus的使用demo

定义一个类
package com.outdoors.jinghuang.demo;

/**
 * Created by jing.huang on 2016/12/5.
 */
public class EventBusHimself {

    /*要传递的数据*/
    private String data;


    public EventBusHimself(String data) {
        this.data = data;
    }


    //在接收者需要获取到信息
    public String getData() {
        return data;
    }
}


发布者
package com.outdoors.jinghuang.demo;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;


import de.greenrobot.event.EventBus;


/**
 * Created by jing.huang on 2016/12/4.
 */
public class EventBusPublisher extends Activity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.event_bus_publisher);
        findViewById(R.id.publish_event).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String data = "this is a practice of EventBus.";
                //发布消息
                EventBus.getDefault().post(new EventBusHimself(data));


            }
        });
    }
}


监听者
package com.outdoors.jinghuang.demo;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;


import de.greenrobot.event.EventBus;


/**
 * Created by jing.huang on 2016/12/4.
 */
public class EventBusReceiver extends Activity {


    private TextView receiveResult;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //监听者注册EventBus
        EventBus.getDefault().register(this);
        setContentView(R.layout.event_bus_receiver);
        receiveResult = (TextView) findViewById(R.id.receive_event_result);
        findViewById(R.id.go_to_next).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(EventBusReceiver.this,EventBusPublisher.class);
                startActivity(intent);
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //监听者反注册EventBus
        EventBus.getDefault().unregister(this);
    }


    public void onEventMainThread(EventBusHimself eventBusHimself) {
        if (eventBusHimself != null) {
            String data = eventBusHimself.getData();
            receiveResult.setText(data);
        }
    }
}


注意:这种方法需要先注册EventBus事件再发送EventBus事件。
订阅函数如onEventMainThread需要用public修饰,不能用private修饰,否则会报错。
订阅事件的参数需要是发布事件是的那个实例




EventBus还可以进行粘性事件,何为粘性事件呢?其实就是发布事件之后再订阅事件也能收到事件。
发布粘性事件的方法是postSticky()方法。注册粘性事件的方法registerSticky();
下面是粘性事件的demo
发布者
package com.outdoors.jinghuang.demo;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;


import de.greenrobot.event.EventBus;


/**
 * Created by jing.huang on 2016/12/5.
 */
public class EventBusPublisher2 extends Activity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.event_bus_publisher);
        findViewById(R.id.publish_event).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EventBus.getDefault().postSticky(new EventBusHimself("this is a practice of EventBus."));
                Intent intent = new Intent(EventBusPublisher2.this, EventBusReceiver2.class);
                startActivity(intent);
            }
        });
    }
}
监听者
package com.outdoors.jinghuang.demo;


import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;


import de.greenrobot.event.EventBus;


/**
 * Created by jing.huang on 2016/12/5.
 */
public class EventBusReceiver2 extends Activity {


    private TextView resultData;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.event_bus_receiver);
        resultData = (TextView) findViewById(R.id.receive_event_result);
        EventBus.getDefault().registerSticky(this);
    }


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


    public void onEventMainThread(EventBusHimself eventBusHimself) {
        if (eventBusHimself != null) {
            String data = eventBusHimself.getData();
            resultData.setText(data);
        }
    }

}

很容易可以发现第一个demo和第二个demo差不多,但是发布和接收EventBus事件的顺序完全相反,却能实现相同的目的。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值