EventBus使用详解

    xiaoxiao2021-08-16  123

    EventBus 是一个 Android 事件发布/订阅框架,通过解耦发布者和订阅者简化 Android 事件传递,这里的事件可以理解为消息,本文中统一称为事件。事件传递既可用于 Android 四大组件间通讯,也可以用户异步线程和主线程间通讯等等。传统的事件传递方式包括:Handler、BroadCastReceiver、Interface 回调,相比之下 EventBus 的优点是代码简洁,使用简单,并将事件发布和订阅充分解耦。

    下面先展示一个实例:

    当点击按钮的时候,跳到第二个Activity,当点击第二个activity上面的按钮的时候向第一个Activity发送消息,当第一个Activity收到消息后,一方面将消息Toast显示,一方面放入textView中显示。

    public class MainActivity extends AppCompatActivity { private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); EventBus.getDefault().register(this); } @Subscribe public void onEventMainThread(FirstEvent event) { String msg = "onEventMainThread收到了消息:" + event.getMsg(); tv.setText(msg); Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } public void click(View view) { Intent intent = new Intent(this, Second_Activity.class); startActivity(intent); } } public class Second_Activity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second_); } public void back(View view) { EventBus.getDefault().post( new FirstEvent("FirstEvent btn clicked")); } } public class FirstEvent { private String mMsg; public FirstEvent(String msg) { mMsg = msg; } public String getMsg() { return mMsg; } }效果:

    其实EventBus还有另外有个不同的函数,他们分别是:

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

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

    参考:http://blog.csdn.net/harvic880925/article/details/40660137

    转载请注明原文地址: https://ju.6miu.com/read-676426.html

    最新回复(0)