EventBus的简单使用

来源:互联网 发布:js弹出消息框自动关闭 编辑:程序博客网 时间:2024/05/17 00:55

一、概述

EventBus是一款针对Android优化的发布/订阅事件总线。主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,线程之间传递消息.优点是开销小,代码更优雅。以及将发送者和接收者解耦。

1、下载EventBus的类库
源码:https://github.com/greenrobot/EventBus

2、基本使用

(1)在要接收消息的页面注册:

<strong>eventBus.register(this);</strong>
(2)发送消息

<strong>eventBus.post(new AnyEventType event);</strong>  

(3)接受消息的页面实现(共有四个函数,各功能不同,这是其中之一,可以选择性的实现,这里先实现一个):

<strong>public void onEvent(AnyEventType event) {}</strong>
(4)解除注册

<strong>eventBus.unregister(this); </strong>


以上是简单的使用命令,下面用一个实例进行详细描述EventBus。



二、实战


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

1、基本框架搭建


MainActivity布局(activity_main.xml)

<pre name="code" class="html"><strong><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> </strong>
新建两个Activity: SecondActivity,ThirdActivity布局(second_activity.xml, third_activity.xml)
second_activity.xml

<strong><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_second_event"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Second Event"/>    <TextView        android:id="@+id/tx"        android:layout_width="match_parent"        android:layout_height="204dp"         />    </LinearLayout></strong>


third_activity.xml


<strong><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_third_event"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Third Event"/>    <TextView          android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="请点击按钮"      android:layout_margin="120dp"        />          </LinearLayout></strong>

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);              }          });      }    }

SecondActivity.java (点击btn_second_event跳转到第三个Activity)

package com.testeventbus;public class SecondActivity extends Activity{Button btn_SecondEvent;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.second_activity);EventBus.getDefault().register(this);btn_SecondEvent = (Button) findViewById(R.id.btn_second_event);btn_SecondEvent.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubIntent intent = new Intent(getApplicationContext(),ThirdActivity.class);startActivity(intent);}});}}}

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


新建一个类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;      }  } 
构造时传进去一个字符串,然后可以通过getMsg()获取出来。


要在MainActivity中接收发过来的消息的,所以在MainActivity中注册消息。其中要在SecondActivity中接收发过来的消息与MainActivity中的方法一样,在这就列出MainActivity的代码块。

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

package com.testeventbus;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);              }          });      }       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();   }   @Override   protected void onDestroy(){   super.onDestroy();   EventBus.getDefault().unregister(this);   }    }

发送消息

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

EventBus.getDefault().post(new FirstEvent("FirstEvent btn clicked")); 

完整的ThirdActivity.java的代码如下:

package com.testeventbus;public class ThirdActivity extends Activity{private Button btn_ThirdEvent;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.third_activity);btn_ThirdEvent = (Button) findViewById(R.id.btn_third_event);btn_ThirdEvent.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubEventBus.getDefault().post(new FirstEvent("请更改你的密码"));}});}}

接收消息

接收消息时,我们使用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();  } 
其中SecondActivity和MainActiviy很相似,在这给出完整的MainActiviy代码如下

package com.testeventbus;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);              }          });      }       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();   }   @Override   protected void onDestroy(){   super.onDestroy();   EventBus.getDefault().unregister(this);   }    } 

以上基本上算初步把EventBus用起来了,其中我们可以将第三个Activity的消息分别延时给到第一个和第二个Activity中。下一篇我们在继续讲述怎么将消息分发到第一个和第二个界面中去。













1 0
原创粉丝点击