Android中通常耗时操作我们都需要另起线程,比如请求服务器获取数据,而请求数据成功后却不能在子线程中更新UI,Android提供了AsyncTask,Handler等机制更新UI,又或者RXJava(开源框架)、接口回调等都可以实现子线程和UI线程通信。其实通过EventBus订阅与发布方式更新UI也很方便。
一,首先我们导入依赖
compile 'org.greenrobot:eventbus:3.0.0'
二,使用
EventBus.getDefault().register(this); //事件注册
@Subscribe(threadMode = ThreadMode.MAIN)//事件订阅 public void onHanleEvent(MessageEvent messageEvent) { mTv.setText(messageEvent.getMessage()); }
EventBus.getDefault().postSticky(new MessageEvent(response.body().string()));//发布消息
三,详细代码
public class HomeFragment extends BaseFragment { private TextView mTv; private Button mBt; private final static String TAG = HomeFragment.class.getSimpleName(); @Override protected int setLayoutId() { return R.layout.fragment_home; } @Override protected void findViews(View view) { mTv = view.findViewById(R.id.tv); mBt = view.findViewById(R.id.bt); } @Override protected void initViews() { EventBus.getDefault().register(this); doHttp(); } @Override protected void initEvent() { mBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(getActivity(),SecondTest.class); getActivity().startActivity(i); } }); } @Override protected void loadDate() { } @Subscribe(threadMode = ThreadMode.MAIN) public void onHanleEvent(MessageEvent messageEvent) { mTv.setText(messageEvent.getMessage()); } private void doHttp(){ Log.i(TAG, "doHttp: "+"测试"); OkHttpClient client = new OkHttpClient(); final Request request = new Request.Builder().url("https://www.baidu.com/").build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { // Log.i(TAG, "onResponse: "+response.body().string()); EventBus.getDefault().postSticky(new MessageEvent(response.body().string())); } }); } }
效果图:
总结:使用方便,可以达到通常需求。