您的位置:首页 > 其它

EventBus3.0学习小结

2016-03-28 18:05 260 查看
一、背景

1、android各个界面之间、各个逻辑层之间的数据传递经常会采用Intent、handler、BroadCastReceiver、CallBack回调等方式,这些方式的实现需要我们在代码中硬编码去实现。

2、EventBus主要用观察者的设计模式实现的解耦合的功能,通过事件的订阅、发布来实现消息数据的传递。

3、源码下载地址 : https://github.com/greenrobot/EventBus

二、使用

1、消息事件订阅(可以参照broadcastreceiver的注册和取消注册来理解)

(1)EventBus.getDefault().register(this);  // 订阅

(2)EventBus.getDefault().unregister(this);// 取消订阅

注:一般在activity的onCreate中订阅,在onDestory()中取消订阅

2、消息的处理

可以自己随意定义一个方法来进行接收到消息事件后的处理
@Subscribe(threadMode=ThreadMode.MAIN)
public void firstReceiveMsg(FirstEvent event){


这里有四个地方需要注意:

(1)必须加注解@Subscribe ,否则EventBus不知道用哪个方法来接收订阅到的消息事件

(2)方法必须是public的,EventBus.getDefault().register(this)时在当前类中查找Subscribe的方法进行发射获取,不是public的话获取不到

(3)threadMode的几种情况:
// 如果不写,默认为posting
// threadMode=ThreadMode.ASYNC : 单独新生成了一个线程来处理消息
// ThreadMode.MAIN : 在主线程中处理消息
// ThreadMode.POSTING : 和发送消息的线程相同(在同一个线程中处理消息)
// ThreadMode.BACKGROUND : 如果事件在主线程中发布,则在子线程中处理,如果在子线程中发布,在在该子线程中处理。

(4)订阅多个事件时根据事件的类型来决定调用哪个方法来接收事件

三、用例

有两个activity,activity1跳转到activity2,activity2出发业务逻辑层的方法,业务逻辑层发布消息。

FirstActivity.java

package com.example.android_test_eventbus.activity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

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;

import com.example.android_test_eventbus.R;
import com.example.android_test_eventbus.bean.FirstEvent;

public class FirstActivity extends Activity {

private Button btn;
private 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) {
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
startActivity(intent);
}
});
}

@Subscribe(threadMode=ThreadMode.MAIN)
public void firstReceiveMsg(FirstEvent event) {
// 默认为posting
// threadMode=ThreadMode.ASYNC : 单独新生成了一个线程来处理消息
// ThreadMode.MAIN : 在主线程中处理消息
// ThreadMode.POSTING : 和发送消息的线程相同(在同一个线程中处理消息)
// ThreadMode.BACKGROUND : 如果事件在主线程中发布,则在子线程中处理,如果在子线程中发布,在在该子线程中处理。

final String msg = "firstReceiveMsg , FirstActivity收到了消息:" + event.getMsg();
Log.d("lixm", msg);
Log.d("lixm", "Thread_name = " + Thread.currentThread().getName() + " , " + Thread.currentThread().getId());
tv.setText(msg);
Toast.makeText(FirstActivity.this, msg, Toast.LENGTH_LONG).show();
EventBus.getDefault().removeAllStickyEvents();
}

@Override
protected void onDestroy(){
super.onDestroy();
EventBus.getDefault().unregister(this);//反注册EventBus
}

}


SecondActivity.java

package com.example.android_test_eventbus.activity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.android_test_eventbus.R;
import com.example.android_test_eventbus.bean.MessageBean;
import com.example.android_test_eventbus.manager.DataManager;

public class SecondActivity extends Activity{
private Button btn_FirstEvent;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);

//注册EventBus
EventBus.getDefault().register(this);

btn_FirstEvent = (Button) findViewById(R.id.btn_first_event);

btn_FirstEvent.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
DataManager.getInstance().testEventBus();
}
});
}

@Subscribe(threadMode=ThreadMode.MAIN)
public void secondReceiveMsg(MessageBean msgBean) {
final String msg = "secondReceiveMsg ,SecondActivity 收到了MessageBean消息:" + msgBean.getMsg();
Log.d("lixm", msg);
Log.d("lixm", "Thread_name = " + Thread.currentThread().getName() + " , " + Thread.currentThread().getId());
Toast.makeText(SecondActivity.this, msg, Toast.LENGTH_LONG).show();
}

@Override
protected void onDestroy(){
super.onDestroy();
EventBus.getDefault().unregister(this);//反注册EventBus
}
}


FirstEvent.java

package com.example.android_test_eventbus.bean;

public class FirstEvent {
private String mMsg;

public FirstEvent(String msg) {
mMsg = msg;
}

public String getMsg(){
return mMsg;
}
}


MessageBean.java

package com.example.android_test_eventbus.bean;

public class MessageBean {
private String msg;

public MessageBean(String msg){
this.msg = msg;
}

/**
* @return msg
*/
public String getMsg() {
return msg;
}
}


DataManager.java

package com.example.android_test_eventbus.manager;

import org.greenrobot.eventbus.EventBus;

import com.example.android_test_eventbus.bean.FirstEvent;
import com.example.andr
4000
oid_test_eventbus.bean.MessageBean;

public class DataManager {

private static DataManager instance;

private DataManager() {
}

/**
*
* @Title: getInstance
* @Description: 单例方式提供对象
* @return
* @throws
*/
public static DataManager getInstance() {
if(instance == null){
synchronized (DataManager.class) {
if(instance == null){
instance = new DataManager();
}
}
}
return instance;
}

public void testEventBus(){
new Thread(){
public void run(){
try {
Thread.currentThread().sleep(6000);
EventBus.getDefault().post(new FirstEvent("这里是异步处理的结果!"));
EventBus.getDefault().post(new MessageBean("这里要测试MSG"));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
}


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="跳转到第二个界面"/>
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="match_parent"/>

</LinearLayout>


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="计算数据"/>

</LinearLayout>

// ================================================================================================================

Activity的简单封装

// ================================================================================================================

public abstract class BaseActivity extends Activity {
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
EventBus.getDefault().register(this);
}

/**
* 事件返回的对象。
*
* @param obj
*/
public abstract void processEvent(EventObject obj);

@Subscribe(threadMode = ThreadMode.MAIN)
public void showEventBusMsg(EventObject obj) {
processEvent(obj);
}

@Override
protected void onResume() {
super.onResume();
}

@Override
protected void onPause() {
super.onPause();
}

@Override
protected void onStop() {
super.onStop();
}

@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息