EventBus的学习笔记

来源:互联网 发布:淘宝卖家新手教程 编辑:程序博客网 时间:2024/04/30 22:33

EventBus是一款针对Android优化的发布/订阅事件总线。主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,线程之间传递消息.优点是开销小,代码更优雅。以及将发送者和接收者解耦。

下面是我的学习Demo

package com.yyw.eventbussample;import android.content.Intent;import android.os.Bundle;import android.support.design.widget.FloatingActionButton;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.Toolbar;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.view.View;import de.greenrobot.event.EventBus;import de.greenrobot.event.Subscribe;public class MainActivity extends AppCompatActivity {    public static final String TAG = "MainActivity";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        EventBus.getDefault().register(this);        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);        setSupportActionBar(toolbar);        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);        fab.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Intent intent = new Intent(MainActivity.this,Main2Activity.class);                startActivity(intent);            }        });    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_main, menu);        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }    @Subscribe    public void onEventMainThread(Event1 event){        Log.i(TAG, "onEventMainThread: " + "id = "+event.getId() + "msg = "+event.getName());    }    @Subscribe    public void onEventMainThread(Event2 event){        Log.i(TAG, "onEventMainThread: " + "id = "+event.getId() + "msg = "+event.getName());    }    @Override    protected void onDestroy() {        if (EventBus.getDefault().isRegistered(this)){            EventBus.getDefault().unregister(this);        }        super.onDestroy();    }}
package com.yyw.eventbussample;import android.content.Intent;import android.support.design.widget.FloatingActionButton;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.support.v7.widget.Toolbar;import android.util.Log;import android.view.View;import de.greenrobot.event.EventBus;import de.greenrobot.event.Subscribe;public class Main2Activity extends AppCompatActivity {    public static final String TAG = "Main2Activity";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        EventBus.getDefault().register(this);        setContentView(R.layout.activity_main);        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);        setSupportActionBar(toolbar);        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);        fab.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Intent intent = new Intent(Main2Activity.this, Main22Activity.class);                startActivity(intent);            }        });    }    /**     * 同一个事件的执行顺序,可以在上一个方法中对事件进行修改     * id = 2msg = 这是事件2     * onEventAsync: id = 2msg = 这是事件2     * onEventBackgroundThread: id = 2msg = 这是事件2     * onEventMainThread: id = 2msg = 这是事件2     **/    @Subscribe    public void onEventMainThread(Event1 event) {        Log.i(TAG, "onEventMainThread: " + "id = " + event.getId() + "msg = " + event.getName());    }    /**     * 如果使用onEventMainThread作为订阅函数,     * 那么不论事件是在哪个线程中发布出来的,onEventMainThread都会在UI线程中执行,接收事件就会在UI线程中运行     * ,这个在Android中是非常有用的,因为在Android中只能在UI线程中跟新UI,     * 所以在onEvnetMainThread方法中是不能执行耗时操作的。     * @param event     */    @Subscribe    public void onEventMainThread(Event2 event) {        Log.i(TAG, "onEventMainThread: " + "id = " + event.getId() + "msg = " + event.getName());        event.setName(event.getName() + "onEventMainThread");    }    /****     * 如果使用onEvent作为订阅函数,那么该事件在哪个线程发布出来的,     * onEvent就会在这个线程中运行,也就是说发布事件和接收事件线程在同一个线程。     * 使用这个方法时,在onEvent方法中不能执行耗时操作,如果执行耗时操作容易导致事件分发延迟。     * @param event     */    @Subscribe    public void onEvent(Event2 event) {        Log.i(TAG, "onEvent: " + "id = " + event.getId() + "msg = " + event.getName());        event.setName(event.getName()+"onEvent");    }    /**     * 如果使用onEventBackgrond作为订阅函数,那么如果事件是在UI线程中发布出来的,     * 那么onEventBackground就会在子线程中运行,如果事件本来就是子线程中发布出来的,     * 那么onEventBackground函数直接在该子线程中执行。     * @param event     */    @Subscribe    public void onEventBackgroundThread(Event2 event) {        Log.i(TAG, "onEventBackgroundThread: " + "id = " + event.getId() + "msg = " + event.getName());        event.setName(event.getName() + "onEventBackgroundThread");    }    /**     * 使用这个函数作为订阅函数,那么无论事件在哪个线程发布,都会创建新的子线程在执行onEventAsync.     * 如果方法的参数为发送事件类的超类也是可以接受事件的     * @param event     */    @Subscribe    public void onEventAsync(Object event) {        Log.i(TAG, "onEventAsync: " + event.toString());//        Log.i(TAG, "onEventAsync: " + "id = " + event.getId() + "msg = " + event.getName());//        event.setName(event.getName()+"onEventAsync");    }    @Override    protected void onDestroy() {        if (EventBus.getDefault().isRegistered(this)) {            EventBus.getDefault().unregister(this);        }        super.onDestroy();    }}
package com.yyw.eventbussample;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import de.greenrobot.event.EventBus;public class Main22Activity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main22);    }    public void onSend1(View v){        EventBus.getDefault().post(new Event1("这是事件1",1));    }    public void onSend2(View v){        EventBus.getDefault().post(new Event2("这是事件2", 2));    }    public void onSend3(View v){        EventBus.getDefault().post(new Event1("这是事件1+1",3));    }    public void onSend4(View v){        EventBus.getDefault().post(new Event2("这是事件2+1",4));    }}
要注意一点:在自己注册的类的事件处理时要在方法上加@Subscribe 不然会报错的。

1,用Main和Mian2两个的注册顺序改变发送事件1可以得到同一事件在传递时候是按照注册顺序进行传递的。



2,在Main2中注册事件并写所有的事件处理方法。可以发现事件的调用顺序,并且可以在事件中添加一些东西传递到下一个方法处理,或者是拦截事件。



3,Main2中的onEventAsync方法的参数修改为Object就可一个发现这个方法可以处理所有的事件。


0 0