有时我们需要在其他非UI线程中更新我们的UI,那么我今天给大家介绍的使用EventBus来更新,这个使用起来非常的简单。如果对我的文章感兴趣,欢迎订阅我的头条号:一点热,yeehot.com。
我们知道在直播中,一般通过socket连接,然后实时的返回数据,这些一般都是我们单独的子线程,这个是无法对我们的UI界面进行更新的,我们要更新必须回到UI线程。
一般来说,我们可以使用handler来实现更新UI
比如是这样
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg){
String s = String.valueOf(msg.what);
TextView tv = (TextView)findViewById(R.id.info);
tv.setText("www.yeehot.com");
}
};
new Thread(new Runnable(){
@Override public void run() {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
}).start;
此外我们也可以使用Activity.runOnUiThread(Runnable)来实现更新UI
不过不是我们今天的重点,我们要说的重点就是使用EventBus来更新。
那么在Android如何使用它?
1、首先我们使用gradle来添加如下代码:
compile 'org.greenrobot:eventbus:3.0.0'
2、添加消息事件,用于接收数据的类型
public class LiveMessageEvent {
public final String username;
public final String info;
public LiveMessageEvent(String username,String info){
this.username= username;
this.info= info;
}
}
3、注解在ui线程执行
@Subscribe(threadMode = ThreadMode.MAIN)
publicvoid onLiveMessageEvent(LiveMessageEvent event){
Toast.makeText(getActivity(), event.username+event.info, Toast.LENGTH_SHORT).show();
}
4、在启动的时候注册EventBus
@Override
publicvoid onStart(){
super.onStart();
EventBus.getDefault().register(this);
}
5、在结束的时候卸载EventBus
@Override
publicvoid onStop(){
EventBus.getDefault().unregister(this);
super.onStop();
}
6、在我们的直播收到信息的子线程调用这个发送事件的方法。
EventBus.getDefault().post(new LiveMessageEvent("yeehot","发表了文章"));
今天的课程就说到这里,欢迎继续关注我的头条号:一点热,yeehot.com
欢迎大家收藏与转发,如果转载到其它网站,请与我联系.