1.EventBus:
2.build.gradle
compile 'org.greenrobot:eventbus:3.0.0'
3.onCreate
EventBus.getDefault().register(this);
4.创建
public class UserEvent { public String username;}
public void sendEvent(View view) { new Thread(){ @Override public void run() { UserEvent event = new UserEvent(); event.username="小熊"; EventBus.getDefault().post(event); } }.start(); EventBus.getDefault().post(new FinishEvent());}
5.onDestory()
EventBus.getDefault().unregister(this);super.onDestroy();
6.线程
@Subscribe(threadMode = ThreadMode.MAIN) //不管你发布的是什么线程 我都跑在 主线程public void changeText(UserEvent event){ Log.e("event","thread1:"+Thread.currentThread().getName()); mText.append(event.username);}
@Subscribe(threadMode = ThreadMode.POSTING) //发布过来是 什么线程 就运行在什么线程public void changeText(final UserEvent event){ Log.e("event","thread2:"+Thread.currentThread().getName()); runOnUiThread(new Runnable() { @Override public void run() { mText.append(event.username); } });}
@Subscribe(threadMode = ThreadMode.BACKGROUND) //发布过来是 主线程 创建子线程 发布过来是 子线程直接运行在该子线程public void changeText(final UserEvent event){ Log.e("event","thread3:"+Thread.currentThread().getName()); runOnUiThread(new Runnable() { @Override public void run() { mText.append(event.username); } });}
@Subscribe(threadMode = ThreadMode.ASYNC) //不管发布的是什么线程 都创建子线程public void changeText(final UserEvent event){ Log.e("event","thread4:"+Thread.currentThread().getName()); runOnUiThread(new Runnable() { @Override public void run() { mText.append(event.username); } });}