EventBus是一款针对Android优化的发布/订阅事件总线。主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,线程之间传递消息.优点是开销小,代码更优雅。以及将发送者和接收者解耦。
1、下载EventBus的类库
源码:https://github.com/greenrobot/EventBus
2、基本使用
(1)自定义一个类,可以是空类,比如:
public class AnyEventType { public AnyEventType(){} }
(2)在要接收消息的页面注册:
eventBus.register(this);
(3)发送消息
eventBus.post(new AnyEventType event);
(4)接受消息的页面实现(共有四个函数,各功能不同):
public void onEvent(AnyEventType event) {} public void onEventMainThread(AnyEventType event) {} public void onEventBackgroundThread(AnyEventType event) {} public void onEventAsync(AnyEventType event) {}
(5)解除注册
eventBus.unregister(this);
顺序就是这么个顺序,可真正让自己写,估计还是云里雾里的,下面举个例子来说明下。
首先,在EventBus中,获取实例的方法一般是采用EventBus.getInstance()来获取默认的EventBus实例,当然你也可以new一个又一个,个人感觉还是用默认的比较好,以防出错。
先给大家看个例子:
当击跳转到第二个界面按钮的时候,跳到第二个Activity,当点击第二个activity上面的t按钮的时候向第一个Activity发送消息,第一个按钮使用的是
新建一个Activity,SecondActivity布局(activity_two.xml)
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/bt_text_post" android:id="@+id/bt_post"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/bt_text_post2" android:layout_below="@id/bt_post" android:id="@+id/bt_post2"/> </RelativeLayout>
MainActivity.java
package com.nova.eventbus_1; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; public class MainActivity extends AppCompatActivity { private Button button_jump; private TextView tv_notify; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button_jump= (Button) findViewById(R.id.bt_jump); tv_notify= (TextView) findViewById(R.id.tv_notify); button_jump.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { <strong> Intent intent=new Intent(MainActivity.this,SecondActivity.class); startActivityForResult(intent,1);</strong> } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode){ case 1: if(resultCode==1){ String returnedData=data.getStringExtra("com.nova.eventbus_1.data_return"); tv_notify.setText(returnedData); Toast.makeText(MainActivity.this,returnedData,Toast.LENGTH_LONG).show(); Log.i("现在的线程",Thread.currentThread().getName()); } } } }
SecondActivity.java
package com.nova.eventbus_1; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import org.greenrobot.eventbus.EventBus; /** * Created by Nova on 2016/4/11. */ public class SecondActivity extends AppCompatActivity { private Button button_post; private Button button_post2;//使用EventBus传递 @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_two); button_post= (Button) findViewById(R.id.bt_post); button_post2= (Button) findViewById(R.id.bt_post2); button_post.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(); intent.putExtra("com.nova.eventbus_1.data_return","跳转按钮:被点击了"); setResult(1,intent); finish(); } }); } }
package com.nova.eventbus_1; /** * Created by Nova on 2016/4/12. * cnhjj2008@gmail.com */ public class FirstEvent { private String mMsg; public FirstEvent(String mMsg) { this.mMsg = mMsg; } public String getMsg() { return mMsg; } }
在上面的GIF图片的演示中,大家也可以看到,我们是要在MainActivity中接收发过来的消息的,所以我们在MainActivity中注册消息。
通过我们会在OnCreate()函数中注册EventBus,在OnDestroy()函数中反注册。所以整体的注册与反注册的代码如下:
package com.nova.eventbus_1; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; public class MainActivity extends AppCompatActivity { private Button button_jump; private TextView tv_notify; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); <strong> //注册EventBus EventBus.getDefault().register(MainActivity.this);</strong> button_jump= (Button) findViewById(R.id.bt_jump); tv_notify= (TextView) findViewById(R.id.tv_notify); button_jump.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(MainActivity.this,SecondActivity.class); startActivityForResult(intent,1); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode){ case 1: if(resultCode==1){ String returnedData=data.getStringExtra("com.nova.eventbus_1.data_return"); tv_notify.setText(returnedData); Toast.makeText(MainActivity.this,returnedData,Toast.LENGTH_LONG).show(); Log.i("现在的线程",Thread.currentThread().getName()); } } } @Subscribe public void onEventMainThread(FirstEvent event){ String msg="onEventMainThread收到了消息:" + event.getMsg(); tv_notify.setText(msg); Toast.makeText(MainActivity.this,msg,Toast.LENGTH_LONG).show(); Log.i("现在的线程",Thread.currentThread().getName()); } @Override protected void onDestroy() { super.onDestroy(); <strong>EventBus.getDefault().unregister(MainActivity.this);</strong> } }
发送消息是使用EventBus中的Post方法来实现发送的,发送过去的是我们新建的类的实例!
EventBus.getDefault().post(new FirstEvent("跳转按钮:被点击了EventBus post"));
完整的SecondActivity.java的代码如下:
package com.nova.eventbus_1; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import org.greenrobot.eventbus.EventBus; /** * Created by Nova on 2016/4/11. */ public class SecondActivity extends AppCompatActivity { private Button button_post; private Button button_post2;//使用EventBus传递 @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_two); button_post= (Button) findViewById(R.id.bt_post); button_post2= (Button) findViewById(R.id.bt_post2); button_post.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(); intent.putExtra("com.nova.eventbus_1.data_return","跳转按钮:被点击了"); setResult(1,intent); finish(); } }); button_post2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //EventBus使用方法 EventBus.getDefault().post(new FirstEvent("跳转按钮:被点击了EventBus post")); finish(); } }); } }
接收消息时,我们使用EventBus中最常用的onEventMainThread()函数来接收消息,具体为什么用这个,我们下篇再讲,这里先给大家一个初步认识,要先能把EventBus用起来先。
在MainActivity中重写onEventMainThread(FirstEvent event),参数就是我们自己定义的类:
在收到Event实例后,我们将其中携带的消息取出,一方面Toast出去,一方面传到TextView中;
@Subscribe public void onEventMainThread(FirstEvent event){ String msg="onEventMainThread收到了消息:" + event.getMsg(); tv_notify.setText(msg); Toast.makeText(MainActivity.this,msg,Toast.LENGTH_LONG).show(); Log.i("现在的线程",Thread.currentThread().getName()); }
切记一定在开头写上@Subscribe,不然报错。
程序结束。