版权声明:本文为博主原创文章,未经博主允许不得转载。

目录(?)[+]

前言:EventBus是上周项目中用到的,网上的文章大都一样,或者过时,有用的没几篇,经过琢磨,请教他人,也终于弄清楚点眉目,记录下来分享给大家。

相关文章:

1、《EventBus使用详解(一)——初步使用EventBus》

2、《EventBus使用详解(二)——EventBus使用进阶》

一、概述

EventBus是一款针对Android优化的发布/订阅事件总线。主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,线程之间传递消息.优点是开销小,代码更优雅。以及将发送者和接收者解耦。
1、下载EventBus的类库
源码:https://github.com/greenrobot/EventBus

2、基本使用

(1)自定义一个类,可以是空类,比如:

  1. public class AnyEventType {
  2. public AnyEventType(){}
  3. }

(2)在要接收消息的页面注册:

  1. eventBus.register(this);

(3)发送消息

  1. eventBus.post(new AnyEventType event);

(4)接受消息的页面实现(共有四个函数,各功能不同,这是其中之一,可以选择性的实现,这里先实现一个):

  1. public void onEvent(AnyEventType event) {}

(5)解除注册

  1. eventBus.unregister(this);

顺序就是这么个顺序,可真正让自己写,估计还是云里雾里的,下面举个例子来说明下。

首先,在EventBus中,获取实例的方法一般是采用EventBus.getInstance()来获取默认的EventBus实例,当然你也可以new一个又一个,个人感觉还是用默认的比较好,以防出错。

二、实战

先给大家看个例子:

当击btn_try按钮的时候,跳到第二个Activity,当点击第二个activity上面的First Event按钮的时候向第一个Activity发送消息,当第一个Activity收到消息后,一方面将消息Toast显示,一方面放入textView中显示。

按照下面的步骤,下面来建这个工程:

1、基本框架搭建

想必大家从一个Activity跳转到第二个Activity的程序应该都会写,这里先稍稍把两个Activity跳转的代码建起来。后面再添加EventBus相关的玩意。

MainActivity布局(activity_main.xml)

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical">
  6. <Button
  7. android:id="@+id/btn_try"
  8. android:layout_width="match_parent"
  9. android:layout_height="wrap_content"
  10. android:text="btn_bty"/>
  11. <TextView
  12. android:id="@+id/tv"
  13. android:layout_width="wrap_content"
  14. android:layout_height="match_parent"/>
  15. </LinearLayout>

新建一个Activity,SecondActivity布局(activity_second.xml)

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical"
  6. tools:context="com.harvic.try_eventbus_1.SecondActivity" >
  7. <Button
  8. android:id="@+id/btn_first_event"
  9. android:layout_width="match_parent"
  10. android:layout_height="wrap_content"
  11. android:text="First Event"/>
  12. </LinearLayout>

MainActivity.java (点击btn跳转到第二个Activity)

  1. public class MainActivity extends Activity {
  2. Button btn;
  3. @Override
  4. protected void onCreate(Bundle savedInstanceState) {
  5. super.onCreate(savedInstanceState);
  6. setContentView(R.layout.activity_main);
  7. btn = (Button) findViewById(R.id.btn_try);
  8. btn.setOnClickListener(new View.OnClickListener() {
  9. @Override
  10. public void onClick(View v) {
  11. // TODO Auto-generated method stub
  12. Intent intent = new Intent(getApplicationContext(),
  13. SecondActivity.class);
  14. startActivity(intent);
  15. }
  16. });
  17. }
  18. }

到这,基本框架就搭完了,下面开始按步骤使用EventBus了。

2、新建一个类FirstEvent

  1. package com.harvic.other;
  2. public class FirstEvent {
  3. private String mMsg;
  4. public FirstEvent(String msg) {
  5. // TODO Auto-generated constructor stub
  6. mMsg = msg;
  7. }
  8. public String getMsg(){
  9. return mMsg;
  10. }
  11. }

这个类很简单,构造时传进去一个字符串,然后可以通过getMsg()获取出来。

3、在要接收消息的页面注册EventBus:

在上面的GIF图片的演示中,大家也可以看到,我们是要在MainActivity中接收发过来的消息的,所以我们在MainActivity中注册消息。

通过我们会在OnCreate()函数中注册EventBus,在OnDestroy()函数中反注册。所以整体的注册与反注册的代码如下:

  1. package com.example.tryeventbus_simple;
  2. import com.harvic.other.FirstEvent;
  3. import de.greenrobot.event.EventBus;
  4. import android.app.Activity;
  5. import android.content.Intent;
  6. import android.os.Bundle;
  7. import android.util.Log;
  8. import android.view.View;
  9. import android.widget.Button;
  10. import android.widget.TextView;
  11. import android.widget.Toast;
  12. public class MainActivity extends Activity {
  13. Button btn;
  14. TextView tv;
  15. @Override
  16. protected void onCreate(Bundle savedInstanceState) {
  17. super.onCreate(savedInstanceState);
  18. setContentView(R.layout.activity_main);
  19. //注册EventBus
  20. EventBus.getDefault().register(this);
  21. btn = (Button) findViewById(R.id.btn_try);
  22. tv = (TextView)findViewById(R.id.tv);
  23. btn.setOnClickListener(new View.OnClickListener() {
  24. @Override
  25. public void onClick(View v) {
  26. // TODO Auto-generated method stub
  27. Intent intent = new Intent(getApplicationContext(),
  28. SecondActivity.class);
  29. startActivity(intent);
  30. }
  31. });
  32. }
  33. @Override
  34. protected void onDestroy(){
  35. super.onDestroy();
  36. EventBus.getDefault().unregister(this);//反注册EventBus
  37. }
  38. }

4、发送消息

发送消息是使用EventBus中的Post方法来实现发送的,发送过去的是我们新建的类的实例!

  1. EventBus.getDefault().post(new FirstEvent("FirstEvent btn clicked"));

完整的SecondActivity.java的代码如下:

  1. package com.example.tryeventbus_simple;
  2. import com.harvic.other.FirstEvent;
  3. import de.greenrobot.event.EventBus;
  4. import android.app.Activity;
  5. import android.os.Bundle;
  6. import android.view.View;
  7. import android.widget.Button;
  8. public class SecondActivity extends Activity {
  9. private Button btn_FirstEvent;
  10. @Override
  11. protected void onCreate(Bundle savedInstanceState) {
  12. super.onCreate(savedInstanceState);
  13. setContentView(R.layout.activity_second);
  14. btn_FirstEvent = (Button) findViewById(R.id.btn_first_event);
  15. btn_FirstEvent.setOnClickListener(new View.OnClickListener() {
  16. @Override
  17. public void onClick(View v) {
  18. // TODO Auto-generated method stub
  19. EventBus.getDefault().post(
  20. new FirstEvent("FirstEvent btn clicked"));
  21. }
  22. });
  23. }
  24. }

5、接收消息

接收消息时,我们使用EventBus中最常用的onEventMainThread()函数来接收消息,具体为什么用这个,我们下篇再讲,这里先给大家一个初步认识,要先能把EventBus用起来先。

在MainActivity中重写onEventMainThread(FirstEvent event),参数就是我们自己定义的类:

在收到Event实例后,我们将其中携带的消息取出,一方面Toast出去,一方面传到TextView中;

  1. public void onEventMainThread(FirstEvent event) {
  2. String msg = "onEventMainThread收到了消息:" + event.getMsg();
  3. Log.d("harvic", msg);
  4. tv.setText(msg);
  5. Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
  6. }

完整的MainActiviy代码如下:

  1. package com.example.tryeventbus_simple;
  2. import com.harvic.other.FirstEvent;
  3. import de.greenrobot.event.EventBus;
  4. import android.app.Activity;
  5. import android.content.Intent;
  6. import android.os.Bundle;
  7. import android.util.Log;
  8. import android.view.View;
  9. import android.widget.Button;
  10. import android.widget.TextView;
  11. import android.widget.Toast;
  12. public class MainActivity extends Activity {
  13. Button btn;
  14. TextView tv;
  15. @Override
  16. protected void onCreate(Bundle savedInstanceState) {
  17. super.onCreate(savedInstanceState);
  18. setContentView(R.layout.activity_main);
  19. EventBus.getDefault().register(this);
  20. btn = (Button) findViewById(R.id.btn_try);
  21. tv = (TextView)findViewById(R.id.tv);
  22. btn.setOnClickListener(new View.OnClickListener() {
  23. @Override
  24. public void onClick(View v) {
  25. // TODO Auto-generated method stub
  26. Intent intent = new Intent(getApplicationContext(),
  27. SecondActivity.class);
  28. startActivity(intent);
  29. }
  30. });
  31. }
  32. public void onEventMainThread(FirstEvent event) {
  33. String msg = "onEventMainThread收到了消息:" + event.getMsg();
  34. Log.d("harvic", msg);
  35. tv.setText(msg);
  36. Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
  37. }
  38. @Override
  39. protected void onDestroy(){
  40. super.onDestroy();
  41. EventBus.getDefault().unregister(this);
  42. }
  43. }

好了,到这,基本上算初步把EventBus用起来了,下篇再讲讲EventBus的几个函数,及各个函数间是如何识别当前如何调用哪个函数的。

如果我的文章有帮到你,请关注哦。

源码地址:http://download.csdn.net/detail/harvic880925/8111357

请大家尊重原创者版权,转载请标明出处:http://blog.csdn.net/harvic880925/article/details/40660137   谢谢!

EventBus (一) 使用详解——初步使用EventBus的更多相关文章

  1. EventBus (二) 使用详解——EventBus使用进阶

    相关文章: 1.<EventBus使用详解(一)——初步使用EventBus> 2.<EventBus使用详解(二)——EventBus使用进阶> 一.概述 前一篇给大家装简单 ...

  2. EventBus的使用详解,功能为在Fragment,Activity,Service,线程之间传递消息

    最近跟同事用到了EventBus的使用,之前不太了解EventBus,查阅资料发现EventBus还挺好用的,用法比较简单,下面就把我看到的关于EventBus的博客分享给大家,里面介绍了很多的使用详 ...

  3. EventBus使用详解(一)——初步使用EventBus

    一.概述 EventBus是一款针对Android优化的发布/订阅事件总线.主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,线程之间 ...

  4. Android消息传递之EventBus 3.0使用详解

    前言: 前面两篇不仅学习了子线程与UI主线程之间的通信方式,也学习了如何实现组件之间通信,基于前面的知识我们今天来分析一下EventBus是如何管理事件总线的,EventBus到底是不是最佳方案?学习 ...

  5. Android EventBus 3.0 实例使用详解

    EventBus的使用和原理在网上有很多的博客了,其中泓洋大哥和启舰写的非常非常棒,我也是跟着他们的博客学会的EventBus,因为是第一次接触并使用EventBus,所以我写的更多是如何使用,源码解 ...

  6. 安卓高级EventBus使用详解

    我本来想写但是在网上看了下感觉写得不如此作者写得好:http://www.jianshu.com/p/da9e193e8b03 前言:EventBus出来已经有一段时间了,github上面也有很多开源 ...

  7. EventBus详解

    EventBus详解 简介 github原文 EventBus... * simplifies the communication between components - decouples eve ...

  8. EventBus使用详解(一)

    一.概述 EventBus是一款针对Android优化的发布/订阅事件总线.主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,线程之间 ...

  9. 【Android】事件总线(解耦组件) EventBus 详解

    当Android项目越来越庞大的时候,应用的各个部件之间的通信变得越来越复杂,例如:当某一条件发生时,应用中有几个部件对这个消息感兴趣,那么我们通常采用的就是观察者模式,使用观察者模式有一个弊病就是部 ...

随机推荐

  1. #ifndef的用法

    作用:防止头文件的重复包含和编译 定义 #ifndef x #define x ... #endif 这是宏定义的一种,它可以根据是否已经定义了一个变量来进行分支选择,一般用于调试等等.实际上确切的说 ...

  2. [Matlab]Upper Triangularization & Back Substitution代码

    用来做数值计算作业的代码,来自Numerical Methods Using Matlab (4th Edition) [John H. Mathews, Kurtis K. Fink],改了一下注释 ...

  3. rsync: chroot No such file or directory (2)

    rsync: ) 查了N多资料,均未解决,最终发现是因为report后面多了个空格...

  4. python定制类(1):__getitem__和slice切片

    python定制类(1):__getitem__和slice切片 1.__getitem__的简单用法: 当一个类中定义了__getitem__方法,那么它的实例对象便拥有了通过下标来索引的能力. c ...

  5. 【SQL SERVER】触发器(二)

    前言:上面一片文章整理了触发器的基础知识点,下面我们看看如何使用触发器以及insert和delete表: 这里我们补充一下触发器的缺点: 性能较低.我们在运行触发器时,系统处理的大部分时间花费在参照其 ...

  6. 转:C++模板学习

    C++ 模板 转:http://www.runoob.com/cplusplus/cpp-templates.html 2018-01-05 模板是泛型编程的基础,泛型编程即以一种独立于任何特定类型的 ...

  7. zTree通过指定ID找到节点并选中

    zTree = $.fn.zTree.getZTreeObj("treeDemo");//treeDemo界面中加载ztree的div var node = zTree.getNo ...

  8. pair 对组

    pair 对组 c++ 基础 2016-05-10 19:42 154人阅读 评论(0) 收藏 举报  分类: 头文件的函数精粹(12)  版权声明:本文为博主原创文章,未经博主允许不得转载. 与关联 ...

  9. Vue 2.0学习(四)计算属性

    {{}}模板内的表达式常用于简单的运算,当运算过长或逻辑复杂时,会难以维护. <div> {{ text.split(',').reverse().join('') }} </div ...

  10. POWEROJ 2610 判断回文串 【HASH】

    题目链接[https://www.oj.swust.edu.cn/problem/show/2610] 题意:给你一个字符串,让你判断这个字符串是不是回文串,字符串的长度是1<len<1e ...