zoukankan      html  css  js  c++  java
  • 在Android studio环境下使用EventBus

    EventBus是一个订阅/发布消息总线,实现在应用程序里面,组件之间,线程之间的通信。因为event是任意的类型,所以这个使用起来非常方便。

    eventbus中的角色:

    event:当然就是事件啦

    subscriber:事件的订阅者,先注册,接收特定的对象,并通过onEventXXX()来回收处理事件。

    Publisher:事件的发布者,通过post发布信息。

    处理过程主要分为5步:

    1.定义一个事件(event)

    2.注册一个订阅者

    3.发布一个事件

    4.接收处理一个事件

    5.注销一个订阅者

    四种处理事件的方式onEventXXXX

    onEvent函数一共有四种,前面的例子只用到一个onEvent。

    函数名含义ThreadMode
    onEvent 事件处理在事件发送的那个线程执行 PostThread
    onEventMainThread 事件在主线程-UI线程执行 MainThread
    onEventBackgroundThread 事件在一个后台线程执行(就一个后台线程) BackgroundThread
    onEventAsync 事件会单独启动一个线程执行(每个事件都会启动一个线程) Async

    其中前三个事件处理方式,都应该尽快完成。

    在as下的代码示例

    改module下的在build.gradle 文件里面,dependencies目录下添加这一句话

    compile 'de.greenrobot:eventbus:2.4.0'

    在连网的情况下,build工程,as会自动去网上下载相应的jar包。build结束后就可以编程了。

    1.定义event。在FirstEvent.java中的代码如下

     1 public class FirstEvent {
     2 
     3     private String msg;
     4     public FirstEvent(String str){
     5         msg = str;
     6     }
     7 
     8     public String getMsg(){
     9         return msg;
    10     }
    11 }

    2.注册一个订阅者,在MainActivity.java 中的onCreate()方法中加入如下代码

    1 EventBus.getDefault().register(this);

    3.发布一个事件。在SecondActivity中发布一个事件,当点击button后发布事件,代码如下

     1   protected void onCreate(Bundle savedInstanceState) {
     2         super.onCreate(savedInstanceState);
     3         setContentView(R.layout.activity_second);
     4 
     5         btn = (Button)findViewById(R.id.second_btn);
     6         btn.setOnClickListener(new View.OnClickListener() {
     7             @Override
     8             public void onClick(View v) {
     9                 
    10                 //发布一个事件
    11                 EventBus.getDefault().post(new FirstEvent("this is an event. "));
    12             }
    13         });

    4.接收并处理一个事件,在MainActivity中处理改事件,添加如下代码。

    1  public void onEventMainThrend(FirstEvent event){
    2         String str = "this is in main activity , "+event.getMsg();
    3 
    4         Log.d("yuqt",str);
    5         tv.setText(str);
    6         Toast.makeText(this,str,Toast.LENGTH_LONG).show();
    7     }

    5.注销事件,在onDestroy()中进行注销。

    1    protected void onDestroy() {
    2         super.onDestroy();
    3         EventBus.getDefault().unregister(this);
    4     }

    完成。

  • 相关阅读:
    python wx安装
    HttpPost请求将带有数组json格式数据作为请求体传入的简单处理方法
    介绍基于camera和IMU的SLAM算法数据采集环境搭建
    《Linux操作系统分析》课程学习总结报告
    安装Sophus出现error: lvalue required as left operand of assignment unit_complex_.real() = 1.问题的解决办法
    结合中断上下文切换和进程上下文切换分析Linux内核的一般执行过程
    深入理解系统调用
    基于mykernel 2.0编写一个操作系统内核
    QT 无法运行“rc.exe”?
    linux上boost库编程cmake配置出错
  • 原文地址:https://www.cnblogs.com/yuqt/p/5042985.html
Copyright © 2011-2022 走看看