EventBus的使用

前言:第一篇文章,EventBus很多项目都在用,本文参照http://blog.csdn.net/harvic880925/article/details/40660137,自己做了一遍。把有用的挑拣出来,记录一下啊

一、概述

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

2、基本使用

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

    public class AnyEventType {  
         public AnyEventType(){}  
     }  


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

eventBus.register(this); 


(3)发送消息

eventBus.post(new AnyEventType event); 


(4)接受消息的页面实现(共有四个函数,各功能不同):

public void onEvent(AnyEventType event) {} 
public void onEventMainThread(AnyEventType event) {} 
public void onEventBackgroundThread(AnyEventType event) {} 
public void onEventAsync(AnyEventType event) {} 

onEvent: 如果使用onEvent作为订阅函数,那么该事件在哪个线程发布出来的,onEvent就会在这个线程中运行,也就是说发布事件和接收事件线程在同一个线程。使用这个方法时,在onEvent方法中不能执行耗时操作,如果执行耗时操作容易导致事件分发延迟。
onEventMainThread :如果使用onEventMainThread作为订阅函数,那么不论事件是在哪个线程中发布出来的,onEventMainThread都会在UI线程中执行,接收事件就会在UI线程中运行,这个在Android中是非常有用的,因为在Android中只能在UI线程中跟新UI,所以在onEvnetMainThread方法中是不能执行耗时操作的。
onEventBackground: 如果使用onEventBackgrond作为订阅函数,那么如果事件是在UI线程中发布出来的,那么onEventBackground就会在子线程中运行,如果事件本来就是子线程中发布出来的,那么onEventBackground函数直接在该子线程中执行。
onEventAsync: 使用这个函数作为订阅函数,那么无论事件在哪个线程发布,都会创建新的子线程在执行onEventAsync.
(5)解除注册

eventBus.unregister(this);


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

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

二、实战

先给大家看个例子:

当击跳转到第二个界面按钮的时候,跳到第二个Activity,当点击第二个activity上面的t按钮的时候向第一个Activity发送消息,第一个按钮使用的是startActivityForResult()方法,第二个按钮使用的是EventBus当第一个Activity收到消息后,一方面将消息Toast显示,一方面放入textView中显示。

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

1、基本框架搭建

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

MainActivity布局(activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.nova.eventbus_1.MainActivity">

    <Button
        android:id="@+id/bt_jump"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/bt_text_jump"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tv_notify"
        android:layout_below="@+id/bt_jump"
        android:layout_alignParentStart="true" />
</RelativeLayout>

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

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/bt_text_post"
        android:id="@+id/bt_post"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/bt_text_post2"
        android:layout_below="@id/bt_post"
        android:id="@+id/bt_post2"/>
</RelativeLayout>

MainActivity.java

package com.nova.eventbus_1;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

public class MainActivity extends AppCompatActivity {

    private Button button_jump;
    private TextView tv_notify;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button_jump= (Button) findViewById(R.id.bt_jump);
        tv_notify= (TextView) findViewById(R.id.tv_notify);
        button_jump.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               <strong> Intent intent=new Intent(MainActivity.this,SecondActivity.class);
                startActivityForResult(intent,1);</strong>
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case 1:
                if(resultCode==1){
                    String returnedData=data.getStringExtra("com.nova.eventbus_1.data_return");
                    tv_notify.setText(returnedData);
                    Toast.makeText(MainActivity.this,returnedData,Toast.LENGTH_LONG).show();
                    Log.i("现在的线程",Thread.currentThread().getName());
                }
        }

    }

}
SecondActivity.java


package com.nova.eventbus_1;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by Nova on 2016/4/11.
 */
public class SecondActivity extends AppCompatActivity {
    private Button button_post;
    private Button button_post2;//使用EventBus传递
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_two);
        button_post= (Button) findViewById(R.id.bt_post);
        button_post2= (Button) findViewById(R.id.bt_post2);
        button_post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.putExtra("com.nova.eventbus_1.data_return","跳转按钮:被点击了");
                setResult(1,intent);
                finish();
            }
        });
      
    }
}

2、新建一个类FirstEvent

package com.nova.eventbus_1;

/**
 * Created by Nova on 2016/4/12.
 * cnhjj2008@gmail.com
 */
public class FirstEvent {
    private String mMsg;

    public FirstEvent(String mMsg) {
        this.mMsg = mMsg;
    }

    public String getMsg() {
        return mMsg;
    }

}

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

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

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

package com.nova.eventbus_1;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

public class MainActivity extends AppCompatActivity {

    private Button button_jump;
    private TextView tv_notify;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       <strong> //注册EventBus
        EventBus.getDefault().register(MainActivity.this);</strong>
        button_jump= (Button) findViewById(R.id.bt_jump);
        tv_notify= (TextView) findViewById(R.id.tv_notify);
        button_jump.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,SecondActivity.class);
                startActivityForResult(intent,1);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case 1:
                if(resultCode==1){
                    String returnedData=data.getStringExtra("com.nova.eventbus_1.data_return");
                    tv_notify.setText(returnedData);
                    Toast.makeText(MainActivity.this,returnedData,Toast.LENGTH_LONG).show();
                    Log.i("现在的线程",Thread.currentThread().getName());
                }
        }

    }

    @Subscribe
    public void onEventMainThread(FirstEvent event){
        String msg="onEventMainThread收到了消息:" + event.getMsg();
        tv_notify.setText(msg);
        Toast.makeText(MainActivity.this,msg,Toast.LENGTH_LONG).show();
        Log.i("现在的线程",Thread.currentThread().getName());
    }

    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        <strong>EventBus.getDefault().unregister(MainActivity.this);</strong>
    }
}

4、发送消息

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

EventBus.getDefault().post(new FirstEvent("跳转按钮:被点击了EventBus post"));
完整的SecondActivity.java的代码如下:

package com.nova.eventbus_1;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by Nova on 2016/4/11.
 */
public class SecondActivity extends AppCompatActivity {
    private Button button_post;
    private Button button_post2;//使用EventBus传递
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_two);
        button_post= (Button) findViewById(R.id.bt_post);
        button_post2= (Button) findViewById(R.id.bt_post2);
        button_post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.putExtra("com.nova.eventbus_1.data_return","跳转按钮:被点击了");
                setResult(1,intent);
                finish();
            }
        });
        button_post2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //EventBus使用方法
                EventBus.getDefault().post(new FirstEvent("跳转按钮:被点击了EventBus post"));
                finish();
            }
        });
    }
}


5、接收消息

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

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

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

@Subscribe
    public void onEventMainThread(FirstEvent event){
        String msg="onEventMainThread收到了消息:" + event.getMsg();
        tv_notify.setText(msg);
        Toast.makeText(MainActivity.this,msg,Toast.LENGTH_LONG).show();
        Log.i("现在的线程",Thread.currentThread().getName());
    }

切记一定在开头写上 @Subscribe,不然报错。

程序结束。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值