Android EventBus简单使用

EventBus是一个发布和订阅事件为优化Android。

image.png

特点

  • 简单的实现组件间的通讯
  • 让编码简单
  • 很快
  • 很轻量级

编写流程

  1. Add EventBus to your project
  • Via Gradle:
compile 'org.greenrobot:eventbus:3.1.1'
  1. Define events:
public static class MessageEvent { /* Additional fields if needed */ }
  1. Prepare subscribers: Declare and annotate your subscribing method, optionally specify a thread mode:
// ThreadMode.MAIN
// 事件的处理会在UI线程中执行,事件处理不应太长时间
@Subscribe(threadMode = ThreadMode.MAIN)  
public void onMessageEvent(MessageEvent event) {/* Do something */};

// ThreadMode.BACKGROUND
// 事件的处理会在一个后台线程中执行,尽管是在后台线程中运行,
// 事件处理时间不应太长。如果事件分发在主线程,件会被加到一个队列中
// 由一个线程依次处理这些事件,如果某个事件处理时间太长,
// 会阻塞后面的事件的派发或处理。如果事件分发在后台线程,事件会立即执行处理。
@Subscribe(threadMode = ThreadMode.BACKGROUND )   
public void onMessageEvent(MessageEvent event) {/* Do something */};

// ThreadMode: POSTING 
// 事件的处理在和事件的发送在相同的进程,
// 所以事件处理时间不应太长,不然影响事件的发送线程,而这个线程可能是UI线程.
@Subscribe(threadMode = ThreadMode.POSTING )   
public void onMessageEvent(MessageEvent event) {/* Do something */};

// ThreadMode: ASYNC 
// 事件处理会在单独的线程中执行,主要用于在后台线程中执行耗时操作,
// 每个事件会开启一个线程(有线程池),但最好限制线程的数目。
@Subscribe(threadMode = ThreadMode: ASYNC )   
public void onMessageEvent(MessageEvent event) {/* Do something */};
  1. Register and unregister your subscriber. For example on Android, activities and fragments should usually register according to their life cycle:
@Override
public void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

@Override
public void onStop() {
    super.onStop();
    EventBus.getDefault().unregister(this);
}
  1. Post events:
EventBus.getDefault().post(new MessageEvent());

案例:


image.png

代码:

public class MainActivity extends AppCompatActivity {

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

        EventBus.getDefault().register(this);
    }

    public void start(View v){
        startService(new Intent(this,MyService.class));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MyEvent myEvent){
        Toast.makeText(this, myEvent.content, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
public class MyService extends Service {
    public MyService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        new Thread(new Runnable() {
            @Override
            public void run() {
                //开始干活了
                SystemClock.sleep(2000);
                //事情干完了
                EventBus.getDefault().post(new MyEvent("给我卫生纸"));
            }
        }).start();
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

你可能感兴趣的:(Android EventBus简单使用)