Android - 开源库EventCast

概述

EventCast是一个事件分发的开源库, GitHub中也有很多类似的库, 比如EventBus, otto, AndroidEventBus, 但是还是觉得自己写的比较顺手, 所以产生了EventCast.

AndroidEventBusEventBusotto合并的产物, EventCast也借鉴AndroidEventBus些代码, 和他们不同的是:

  1. 支持多参数传递
  2. 定义了两种接收器

怎么使用?

引用

1
compile 'cn.gavinliu.android.lib:EventCast:0.1+'

注册

1
2
3
4
5
6
7
8
9
10
11
12
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventCast.getInstance().register(this);
}

@Override
protected void onDestroy() {
super.onDestroy();
EventCast.getInstance().unRegister(this);
}

事件发布与接收

接收器

  • 使用 @Receiver 标记一个事件接收器
  • 两种接收器
    1. 使用TAG的接收器: 会根据接受器方法的参数类型分区不同的接收器
    2. 不用TAG的接收器: 会使用接受器方法的方法名和参数类型区分不同的接收器
  • 接收器没有参数个数限制

发布器

  • 使用 EventCast.post 发布一个事件
  • @Receiver 中有个PosterType的参数,可以申明使用不同的发布器
    1. PosterType.MAIN : 在主线程调用接收器方法
    2. PosterType.ASYNC : 在新线程调用接收器方法
    3. PosterType.POST : 在当前线程中调接收器方法
  • 对于不同的接收器post方法有不同
    1. 有Tag的接收器: 使用支持tag的post方法
    2. 无Tag的接收器: 使用支持class&method的post方法

示例代码

  • 使用TAG&无参数
1
2
3
4
5
6
7
8
@Receiver(tag = "xx")
public void postByTag() {
Toast.makeText(this, "PostByTag", Toast.LENGTH_SHORT).show();
}

... other code ...

EventCast.getInstance().post("xx");
  • 使用TAG&有参数
1
2
3
4
5
6
7
8
@Receiver(tag = "xx", posterType = PosterType.POST)
public void postByTagAndParam(int x, int y) {
Toast.makeText(this, "PostByTagAndParam: (" + x + "," + y + ")", Toast.LENGTH_SHORT).show();
}

... other code ...

EventCast.getInstance().post("xx", 1, 2);
  • 不使用Tag&无参数
1
2
3
4
5
6
7
8
@Receiver
public void postByMethod() {
Toast.makeText(this, "postByMethod:", Toast.LENGTH_SHORT).show();
}

... other code ...

EventCast.getInstance().post(MainActivity.class, "postByMethod");
  • 不使用Tag&有参数
1
2
3
4
5
6
7
8
@Receiver
public void postByMethodAndParam(String x) {
Toast.makeText(this, "postByMethodAndParam:" + x, Toast.LENGTH_SHORT).show();
}

... other code ...

EventCast.getInstance().post(MainActivity.class, "postByMethodAndParam", "Hello~");

设计与实现

Gavin Liu wechat
欢迎您扫一扫上面的二维码,订阅我的微信公众号!