Android的EventBus使用
简介
EventBus简介
这个EventBus不要太好用啊,简直是开发者福音。上手极快,只需导入,即刻使用!!!!
解耦效果贼棒!!
在一个Activity、Fragment中post(),即可在另一个Activity、Fragment中subscribe()
想要传递什么样的值完全取决于你的实体类定义成啥样,传入啥类就接收啥类实体,简直不要太便捷!!!!
代码示例
比如我先这样:
import android.bluetooth.BluetoothDevice;
/**
* 新构建一个类,用于数据的载体.
*/
public class ReturnBluetoothDevice {
private BluetoothDevice device;
public ReturnBluetoothDevice(BluetoothDevice device){
this.device=device;
}
public BluetoothDevice getDeivce(){
return device;
}
public void setDevice(BluetoothDevice device){
this.device=device;
}
}
然后再这样:
//调用post,发送一个类实体
EventBus.getDefault().post(new ReturnBluetoothDevice(device));
最后这样:
/*
* 这里定义一个接收的方法就行,方法名无所谓
* 前面必须要加@Subscribe,表明身份,GKD!!!
* @param device
*/
@Subscribe
public void onEventThread(ReturnBluetoothDevice device){
//这里加入接收到EventBus消息需要进行的处理,不能做耗时处理
Bluetooth mDevice;
mDevice = device.getDevice();
}
然后就ok了,是不是很简单!!!!