eventBus之小记

本文介绍了EventBus在Android开发中的使用方法,包括如何在不同组件间传递消息,以及四种不同线程模式下事件处理的区别。

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

eventBus:通过解耦发布者和订阅者简化android事件的传递(一个android事件发布/订阅轻量级框架)

优点:代码简洁,是一种发布订阅设计模式(观察者模式)

使用场景:用于线程之间通讯代替Handler,或用于组件之间的通讯代替intent

 基本使用:

1、基本框架:两个activity之间的跳转

2、在( 第一个activity) onCreate中注册,在onDestroy中解注册(反注册)具体用法如下:

[html]  view plain  copy
  1. package com.mytest;  
  2.   
  3. import android.content.Intent;  
  4. import android.support.v7.app.AppCompatActivity;  
  5. import android.os.Bundle;  
  6. import android.util.Log;  
  7. import android.view.View;  
  8. import android.widget.Button;  
  9. import android.widget.TextView;  
  10. import android.widget.Toast;  
  11.   
  12. import org.greenrobot.eventbus.EventBus;  
  13. import org.greenrobot.eventbus.Subscribe;  
  14.   
  15. /**  
  16.  * eventBus 在onCreate里面注册  
  17.  *          在OnDestroy里面反注册  
  18.  */  
  19. public class MainActivity extends AppCompatActivity {  
  20.     private Button btn_update;  
  21.     private TextView tv;  
  22.   
  23.     @Override  
  24.     protected void onCreate(Bundle savedInstanceState) {  
  25.         super.onCreate(savedInstanceState);  
  26.         setContentView(R.layout.activity_main);  
  27.         btn_update = findViewById(R.id.update);  
  28.         tv = findViewById(R.id.tv_upData);  
  29.   
  30. <span style="color:#ff0000;">//        注册eventBus  
  31.         EventBus.getDefault().register(this);</span>  
  32.   
  33.         btn_update.setOnClickListener(new View.OnClickListener() {  
  34.             @Override  
  35.             public void onClick(View view) {  
  36.                 Intent  intent =new Intent(getApplicationContext(),EVentBusActivity.class);  
  37.                 startActivity(intent);  
  38.             }  
  39.         });  
  40.   
  41.     }  
  42.     @Override  
  43.     protected void onDestroy() {  
  44.         super.onDestroy();  
  45.       <span style="color:#ff0000;"> EventBus.getDefault().unregister(this);//反注册</span>  
  46.     }  
  47.    <span style="color:#ff0000;"> /**  
  48.      * 定义方法时,要在该方法上添加@Subscribe  否则方法不被执行  
  49.      * @param event  
  50.      */</span>  
  51.    <span style="color:#3333ff;"> @Subscribe()</span>  
  52.     public void  onEventMainThread(FirstEvent event){  
  53.         String  msg="onEvent收到消息"+event.getMsg();  
  54.         Log.e("harv",msg );  
  55.   
  56.         tv.setText(msg);  
  57.         Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();  
  58.     }  
  59. }  

3、在第二个activity中发送消息(eventBusActivity)具体用法如下:

[html]  view plain  copy
  1. package com.mytest;  
  2.   
  3. import android.support.v7.app.AppCompatActivity;  
  4. import android.os.Bundle;  
  5. import android.view.View;  
  6. import android.widget.Button;  
  7.   
  8. import org.greenrobot.eventbus.EventBus;  
  9.   
  10. public class EVentBusActivity extends AppCompatActivity {  
  11.     private Button btn_event_bus;  
  12.     @Override  
  13.     protected void onCreate(Bundle savedInstanceState) {  
  14.         super.onCreate(savedInstanceState);  
  15.         setContentView(R.layout.activity_event_bus);  
  16.         initView();  
  17.     }  
  18.     private void initView() {  
  19.         btn_event_bus = findViewById(R.id.btn_event_bus);  
  20.   
  21.         btn_event_bus.setOnClickListener(new View.OnClickListener() {  
  22.             @Override  
  23.             public void onClick(View view) {  
  24. //                发送消息是使用EventBus中的Post方法来实现发送的  
  25.                 EventBus.getDefault().post(new FirstEvent(" event_bus 被点击了"));  
  26.             }  
  27.         });  
  28.     }  
  29. }  

4、其中在两个activity中都用到了一个FirstEvent的类。用于获取getmsg(),代码如下:

[html]  view plain  copy
  1. package com.mytest;  
  2.   
  3. /**  
  4.  * Created by Administrator on 2018/5/9/009.  
  5.  */  
  6.   
  7. public class FirstEvent {  
  8.     String msg;  
  9.   
  10.     public FirstEvent(String msg) {  
  11.         this.msg = msg;  
  12.     }  
  13.   
  14.     public String getMsg() {  
  15.         return msg;  
  16.     }  
  17. }  
注: /**
[html]  view plain  copy
  1. <span style="color:rgb(255,0,0);">     * 定义方法时,要在该方法上添加@Subscribe  否则方法不被执行  
  2.      * @param event  
  3.      */</span>  

参考文献:http://blog.youkuaiyun.com/harvic880925/article/details/40660137

-------------------------------------------------------------------------------------------------------------------

二、eventBus有四个方法

1、onEventMainThread();

2、onEventBackgroundThread();

3、onEventAsync();

4、onEvent();


onEvent:该事件在哪个线程发布出来的,onEvent就会在这个线程中运行,也就是说发布事件和接收事件线程在同一个线程。使用这个方法时,在此方法中不能执行耗时操作,如果执行耗时操作容易导致事件分发延迟。

onEventMainThread:不论事件是在哪个线程中发布出来的,onEventMainThread都会在UI线程中执行,接收事件会在UI线程中运行,这个在Android中是非常有用的,因为在Android中UI只能在线程中更新,所以在该方法中是不能执行耗时操作的。


onEventBackground: 如果使用onEventBackgrond作为订阅函数,那么如果事件是在UI线程中发布出来的,那么onEventBackground就会在子线程中运行,如果事件本来就是子线程中发布出来的,那么onEventBackground函数直接在该子线程中执行。

onEventAsync:使用这个函数作为订阅函数,那么无论事件在哪个线程发布,都会创建新的子线程在执行onEventAsync.

源码如下:

[html]  view plain  copy
  1. package com.mytest;  
  2.   
  3. import android.content.Intent;  
  4. import android.support.v7.app.AppCompatActivity;  
  5. import android.os.Bundle;  
  6. import android.util.Log;  
  7. import android.view.View;  
  8. import android.widget.Button;  
  9. import android.widget.TextView;  
  10. import android.widget.Toast;  
  11.   
  12. import org.greenrobot.eventbus.EventBus;  
  13. import org.greenrobot.eventbus.Subscribe;  
  14. import org.greenrobot.eventbus.ThreadMode;  
  15.   
  16. /**  
  17.  * eventBus 在onCreate里面注册  
  18.  *          在OnDestroy里面反注册  
  19.  */  
  20. public class MainActivity extends AppCompatActivity {  
  21.     private Button btn_update;  
  22.     private TextView tv;  
  23.   
  24.     @Override  
  25.     protected void onCreate(Bundle savedInstanceState) {  
  26.         super.onCreate(savedInstanceState);  
  27.         setContentView(R.layout.activity_main);  
  28.         btn_update = findViewById(R.id.update);  
  29.         tv = findViewById(R.id.tv_upData);  
  30.   
  31. //        注册eventBus  
  32.         EventBus.getDefault().register(this);  
  33.   
  34.         btn_update.setOnClickListener(new View.OnClickListener() {  
  35.             @Override  
  36.             public void onClick(View view) {  
  37.                 Intent  intent =new Intent(getApplicationContext(),EVentBusActivity.class);  
  38.                 startActivity(intent);  
  39.             }  
  40.         });  
  41.   
  42.     }  
  43.     @Override  
  44.     protected void onDestroy() {  
  45.         super.onDestroy();  
  46.         EventBus.getDefault().unregister(this);  
  47.     }  
  48.   
  49.     /**  
  50.      * 定义方法时,要在该方法上添加@Subscribe  否则方法不被执行  
  51.      * 加注解提示:在写接收消息的方法是,方法名可以自定义,权限必须是public,  
  52.      参数必须是一个只要接收的参数类型是一致的,那么四个方法都可以接收到发送的信息    注释:给人看   注解:给机器看  
  53.      ThreadMode.MAIN表示这个方法在主线程中执行(适合做异步加载,可以将子线程加载到数据直接设置到UI界面里  
  54.      * @param event  
  55.      */  
  56.     @Subscribe(threadMode = ThreadMode.MAIN)  
  57.     public void  onEventMainThread(FirstEvent event){  
  58.         String  msg="onEvent收到消息"+event.getMsg();  
  59.         Log.e("harv",msg );  
  60.         tv.setText(msg);  
  61.   
  62.         Log.d("firstEvent","onEventMainThread接收到的消息:"+event.getMsg());  
  63.         Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();  
  64.     }  
  65.   
  66.     //SecondEvent接收到的函数一  
  67.     @Subscribe(threadMode = ThreadMode.MAIN)  
  68.     public void onEventMainThread(SecondEvent event){  
  69.         Log.d("secEvent","onEventMainThread接收到的消息:"+event.getMsg());  
  70.     }  
  71.     //SecondEvent接收到的函数二  
  72.     @Subscribe(threadMode = ThreadMode.MAIN)  
  73.     public void onEventBackgroundThread(SecondEvent event){  
  74.         Log.d("secEvent","onEventBackgroundThread接收到的消息:"+event.getMsg());  
  75.     }  
  76.     //SecondEvent接收到的函数三  
  77.     @Subscribe(threadMode = ThreadMode.MAIN)  
  78.     public void onEventAsync(SecondEvent event){  
  79.         Log.d("secEvent","onEventAsync接收到的消息:"+event.getMsg());  
  80.     }  
  81.   
  82.   
  83.     @Subscribe(threadMode = ThreadMode.MAIN)  
  84.     public void onEvent(ThirdEvent event){  
  85.         Log.d("thirdEvent","onEvent接收到的消息:"+event.getMsg());  
  86.     }  
  87. }  

运行结果:log日志截图:

    

参考文献:http://blog.youkuaiyun.com/harvic880925/article/details/40787203


源码下载:https://download.youkuaiyun.com/download/qq_36636969/10402716

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值