周末出去参加了个分享会,学到了很多,晚上回去整理一下,分享给大家,做开发的要多交流,跟大神交流可以学到很多,有些不是做项目就能了解的,以后多出去充充电
废话少说,看了鸿洋更新的博客,写了个demo,真心觉得这个框架不错,个人感觉能用的地方很多,并且应用起来很方便
这里写了一个广播的接受和发送,通过点击发送广播按钮发送一条广播,通过使用EventBus框架显示在界面上,主要是想练习一下EventBus框架
使用EventBus框架主要就三部:
1.初始化时注册EventBus.getDefault().register(this);
2.用完之后注销EventBus.getDefault().unregister(this);
3.中间过程主要就是消息推送和接收了,通过EventBus.getDefault().post(param)推送,通过onEventMainThread(param),onEventPostThread(param),onEventBackgroundThread(param),onEventAsync(param)接收并处理
package com.sdufe.thea.guo;
import de.greenrobot.event.EventBus;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
/**
* @author Thea
*
* 2014-11-10
*/
public class MainActivity extends Activity implements OnClickListener {
private Button mSendBroadcast;
private TextView mShowMsg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
EventBus.getDefault().register(this);
}
private void initView() {
mSendBroadcast=(Button) findViewById(R.id.send_broadcast);
mShowMsg=(TextView) findViewById(R.id.show_msg);
mSendBroadcast.setOnClickListener(this);
}
@Override
public void onClick(View v) {
final Intent intent=new Intent("com.sdufe.thea.guo.broadcast");
intent.putExtra("msg", "我是大坏蛋");
sendBroadcast(intent);
new Thread(){
public void run() {
try {
Thread.sleep(2000);
EventBus.getDefault().post(intent);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
}.start();
}
public void onEventMainThread(Intent intent)
{
String msg=intent.getStringExtra("msg");
mShowMsg.setText(msg);
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}
当然这里开启了一个子线程,延迟了2s,你也可以直接写成EventBus.getDefault().post(intent);差不多就是这样,别忘了应用EventBus框架的lib包,差不多就扯这么多,详细情况见鸿洋博客的源码分析:http://blog.csdn.net/lmj623565791/article/details/40920453
以上代码下载地址:http://download.csdn.net/detail/elinavampire/8140631