码迷,mamicode.com
首页 > 其他好文 > 详细

EventBus Usage

时间:2016-09-22 07:45:17      阅读:322      评论:0      收藏:0      [点我收藏+]

标签:android event open source framework


EventBus is a publish/subscribe event bus optimized for Android.

so make it simple,just think EventBus as a framework that allow different compoents to communicate,

usually a subscribe register a certain event,then whenever a publisher has post an event,any subscribes who had register this event will be able to receive the notify.

This is an example,Let‘s say MainActivity is a subscribe who has register to receive RecvEvent event,

And Second Activity is a publicer who will post a RecvEvent when his btn is clicked.Theoretically speaking,MainActivity is able to recevie the event that posted by SecondActivity.


//From above,we know that EventBus contains three objects:Event,Subscribe,Publisher

//Event
public class RecvEvent
{
private final String info;
public RecvEvent(String info)
{ 
this.info = info;
}
public String getInfo()
{
return info;
}
}
//Subscribe:MainActivity
public class MainActivity extends AppCompatActivity {
   private TextView tvShowInfo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvShowInfo = (TextView)findViewById(R.id.tvShowRecv);
//register to recevie ShowRecvEvent event
        EventBus.getDefault().register(this);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
//destroy res
        EventBus.getDefault().unregister(this);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRecvEvent(ShowRecvEvent event)
    {
        tvShowInfo.setText(event.getInfo());
    }
    public void onJump(View view)
    {
        startActivity(new Intent(this,SecondActivity.class));
    }
}
//publisher:SecondActivity
public class SecondActivity extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_activity);
    }
    public void onSend(View view)
    {
        EventBus.getDefault().post(new ShowRecvEvent("this is from second activity"));
    }
}


本文出自 “whatever957” 博客,请务必保留此出处http://whatever957.blog.51cto.com/6835003/1855220

EventBus Usage

标签:android event open source framework

原文地址:http://whatever957.blog.51cto.com/6835003/1855220

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!