安卓使用EventBus实现消息传递

来源:互联网 发布:金税发票数据导出软件 编辑:程序博客网 时间:2024/05/13 16:25

什么是EventBus

EventBus是一个 发布/订阅 模式的消息总线库,它简化了应用程序内各组件间、组件与后台线程间的通信,解耦了事件的发送者和接收者,避免了复杂的、易于出错的依赖及生命周期问题,可以使我们的代码更加简洁、健壮。EventBus 用于各组件通信,那么用于 fragment 之间的通信就非常合适了。


1、基本框架搭建

想必大家从一个Activity跳转到第二个Activity的程序应该都会写,这里先稍稍把两个Activity跳转的代码建起来。后面再添加EventBus相关的玩意。

MainActivity布局(activity_main.xml)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:tools="http://schemas.android.com/tools"      android:layout_width="match_parent"      android:layout_height="match_parent"      android:orientation="vertical">            <Button           android:id="@+id/btn_try"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:text="btn_bty"/>      <TextView           android:id="@+id/tv"          android:layout_width="wrap_content"          android:layout_height="match_parent"/>    </LinearLayout> 

新建一个Activity,SecondActivity布局(activity_second.xml)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:tools="http://schemas.android.com/tools"      android:layout_width="match_parent"      android:layout_height="match_parent"      android:orientation="vertical"      tools:context="com.harvic.try_eventbus_1.SecondActivity" >        <Button           android:id="@+id/btn_first_event"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:text="First Event"/>    </LinearLayout>  
MainActivity.java (点击btn跳转到第二个Activity)
public class MainActivity extends Activity {        Button btn;        @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);            btn = (Button) findViewById(R.id.btn_try);            btn.setOnClickListener(new View.OnClickListener() {                @Override              public void onClick(View v) {                  // TODO Auto-generated method stub                  Intent intent = new Intent(getApplicationContext(),                          SecondActivity.class);                  startActivity(intent);              }          });      }    }  

到这,基本框架就搭完了,下面开始按步骤使用EventBus了。

2、新建一个类FirstEvent

package com.harvic.other;    public class FirstEvent {        private String mMsg;      public FirstEvent(String msg) {          // TODO Auto-generated constructor stub          mMsg = msg;      }      public String getMsg(){          return mMsg;      }  } 

3、在要接收消息的页面注册EventBus:

在上面的GIF图片的演示中,大家也可以看到,我们是要在MainActivity中接收发过来的消息的,所以我们在MainActivity中注册消息。

通过我们会在OnCreate()函数中注册EventBus,在OnDestroy()函数中反注册。所以整体的注册与反注册的代码如下:

package com.example.tryeventbus_simple;    import com.harvic.other.FirstEvent;    import de.greenrobot.event.EventBus;  import android.app.Activity;  import android.content.Intent;  import android.os.Bundle;  import android.util.Log;  import android.view.View;  import android.widget.Button;  import android.widget.TextView;  import android.widget.Toast;    public class MainActivity extends Activity {        Button btn;      TextView tv;        @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);                  //注册EventBus          EventBus.getDefault().register(this);            btn = (Button) findViewById(R.id.btn_try);          tv = (TextView)findViewById(R.id.tv);            btn.setOnClickListener(new View.OnClickListener() {                @Override              public void onClick(View v) {                  // TODO Auto-generated method stub                  Intent intent = new Intent(getApplicationContext(),                          SecondActivity.class);                  startActivity(intent);              }          });      }      @Override      protected void onDestroy(){          super.onDestroy();          EventBus.getDefault().unregister(this);//反注册EventBus      }  }  

4、发送消息

发送消息是使用EventBus中的Post方法来实现发送的,发送过去的是我们新建的类的实例!

EventBus.getDefault().post(new FirstEvent("FirstEvent btn clicked"));  
完整的SecondActivity.Java的代码如下:

package com.example.tryeventbus_simple;    import com.harvic.other.FirstEvent;    import de.greenrobot.event.EventBus;  import android.app.Activity;  import android.os.Bundle;  import android.view.View;  import android.widget.Button;    public class SecondActivity extends Activity {      private Button btn_FirstEvent;        @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_second);          btn_FirstEvent = (Button) findViewById(R.id.btn_first_event);            btn_FirstEvent.setOnClickListener(new View.OnClickListener() {                @Override              public void onClick(View v) {                  // TODO Auto-generated method stub                  EventBus.getDefault().post(                          new FirstEvent("FirstEvent btn clicked"));              }          });      }  }  

5、接收消息

接收消息时,我们使用EventBus中最常用的onEventMainThread()函数来接收消息,具体为什么用这个,我们下篇再讲,这里先给大家一个初步认识,要先能把EventBus用起来先。

在MainActivity中重写onEventMainThread(FirstEvent event),参数就是我们自己定义的类:

在收到Event实例后,我们将其中携带的消息取出,一方面Toast出去,一方面传到TextView中;

public void onEventMainThread(FirstEvent event) {        String msg = "onEventMainThread收到了消息:" + event.getMsg();      Log.d("harvic", msg);      tv.setText(msg);      Toast.makeText(this, msg, Toast.LENGTH_LONG).show();  }  



0 0