EventBus實現廣播的接受

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);
        }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章