eventbus/documentation/how-to-get-started/

本文介绍如何使用EventBus简化Android应用中的事件处理。首先,在Gradle中添加依赖;其次,定义事件类并实现订阅者方法;最后,从代码的任意位置发布事件。遵循这三步即可轻松实现组件间的解耦。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

How to get started with EventBus in 3 steps

EventBus’ API is as easy as 1-2-3. Before we get started with the 3 basic steps, let’s add the EventBus depency to your Gradle script (make sure you are using the latest version):

 compile 'org.greenrobot:eventbus:3.0.0'

Step 1: Define events

Events are POJO (plain old Java object) without any specific requirements.

public class MessageEvent {
    public final String message;

    public MessageEvent(String message) {
        this.message = message;
    }
}

Step 2: Prepare subscribers

Subscribers implement event handling methods (also called “subscriber methods”) that will be called when an event is posted. These are defined with the @Subscribe annotation. Please note that with EventBus 3 the method name can be chosen freely (no naming conventions like in EventBus 2).

// This method will be called when a MessageEvent is posted
@Subscribe
public void onMessageEvent(MessageEvent event){
    Toast.makeText(getActivity(), event.message, Toast.LENGTH_SHORT).show();
}

// This method will be called when a SomeOtherEvent is posted
@Subscribe
public void handleSomethingElse(SomeOtherEvent event){
    doSomethingWith(event);
}

Subscribers also need to register and unregister themselves to the bus. Only while subscribers are registered, they will receive events. In Android, Activities and Fragments usually bind according to their life cycle:

@Override
public void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

@Override
public void onStop() {
   EventBus.getDefault().unregister(this);
    super.onStop();
}

Step 3: Post events

Post an event from any part of your code. All currently registered subscribers matching the event type will receive it.

EventBus.getDefault().post(new MessageEvent("Hello everyone!"));

转载于:https://my.oschina.net/sarashare/blog/654822

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值