AI智能
改变未来

android eventbus通信


添加依赖

implementation ‘org.greenrobot:eventbus:3.0.0’

通信管理类

import org.greenrobot.eventbus.EventBus;public class EventBusUtil {public static void register(Object subscriber) {EventBus.getDefault().register(subscriber);}public static void unregister(Object subscriber) {EventBus.getDefault().unregister(subscriber);}public static void sendEvent(MessageEvent event) {EventBus.getDefault().post(event);}public static void sendStickyEvent(MessageEvent event) {EventBus.getDefault().postSticky(event);}}

通信介质对象

public class MessageEvent<T> {private int code;private T data;public MessageEvent(int code) {this.code = code;}public MessageEvent(int code, T data) {this.code = code;this.data = data;}public int getCode() {return code;}public void setCode(int code) {this.code = code;}public T getData() {return data;}public void setData(T data) {this.data = data;}}

baseActivity注册

public class BaseActivity extends AppCompatActivity{@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);EventBusUtil.register(this);}@Overrideprotected void onDestroy() {super.onDestroy();EventBusUtil.unregister(this);}@Subscribe(threadMode = ThreadMode.MAIN)public void onEventBusCome(MessageEvent event) {if (event != null) {receiveEvent(event);}}@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)public void onStickyEventBusCome(MessageEvent event) {if (event != null) {receiveStickyEvent(event);}}/*** 接收到分发到事件*/protected void receiveEvent(MessageEvent event) {}/*** 接受到分发的粘性事件*/protected void receiveStickyEvent(MessageEvent event) {}}
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » android eventbus通信