一、概述
EventBus是一款针对Android优化的发布/订阅事件总线。主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,线程之间传递消息.优点是开销小,代码更优雅。以及将发送者和接收者解耦。
1、下载EventBus的类库
源码:https://github.com/greenrobot/EventBus
EventBus
EventBus is a publish/subscribe event bus optimized for Android.
EventBus in 3 steps
-
Define events:
public class MessageEvent { /* Additional fields if needed */ }//数据domain
-
Prepare subscribers: Register your subscriber (in your onCreate or in a constructor)://注册订阅者
eventBus.register(this);
Declare your subscribing method://自定义订阅者方法 如 xxx
@Subscribe public void onEvent(AnyEventType event) {/* Do something */};
-
Post events:
eventBus.post(event);//发布者发布数据
1.step
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:24.2.0' compile 'org.greenrobot:eventbus:3.0.0' }2. a->B 实现a到B页面B界面回传到A界面的数据
A
package com.example.administrator.eventbus30demo; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; public class MainActivity extends AppCompatActivity { TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView= (TextView) findViewById(R.id.text); EventBus.getDefault().register(this);//接受消息的界面注册 } public void ToNext(View v){ startActivity(new Intent(this,SecondPage.class)); } //自定义的订阅者方法内部使用注解实现方法名自己定义 @Subscribe public void x(Msg event) { String name = event.getName(); textView.setText(name); }; @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this);//销毁时取消订阅者 } }B界面
package com.example.administrator.eventbus30demo; import android.app.Activity; import android.os.Bundle; import android.view.View; import org.greenrobot.eventbus.EventBus; /** * Created by Administrator on 2016/9/5. */ public class SecondPage extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_secondpage); } public void ToPervious(View v){ finish(); EventBus.getDefault().post(new Msg("gsc com on !"));//发布者发布事件 } }