Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

EventBus 使用詳解:Android 發布/訂閱事件總線的實戰入門

編輯:關於 Android 開發

前言

EventBus 是許多 Android 項目中都在使用的通信框架。本文結合成手實踐,把最關鍵、最常用的知識點提煉出來,幫助你快速上手。

一、概述

EventBus 是一款針對 Android 進行了優化的發布/訂閱事件總線。它的主要功能是替代 Intent、Handler、BroadCast,在 Fragment、Activity、Service 以及各個線程之間傳遞消息。其優點在於開銷小、代碼更為優雅,並且能夠實現發送者與接收者之間的解耦。

源碼地址:https://github.com/greenrobot/EventBus

基本使用步驟

(1)自定義一個事件類,可以是空類,例如:

public class AnyEventType {
    public AnyEventType() {}
}

(2)在需要接收消息的頁面進行註冊:

eventBus.register(this);

(3)發送消息:

eventBus.post(new AnyEventType());

(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 都會在 UI 線程中執行。這在 Android 中非常有用,因為系統只允許在 UI 線程更新界面。同樣地,該方法中也不能執行耗時操作。

onEventBackground:如果事件是在 UI 線程發布的,那麼 onEventBackground 會在子線程中運行;如果事件本來就是在子線程發布的,則直接在該子線程中執行。

onEventAsync:無論事件在哪個線程發布,都會創建一個全新的子線程來執行 onEventAsync。

(5)解除註冊:

eventBus.unregister(this);

順序大致就是這樣,但若真要自己動手寫,往往還是會有些迷茫,下面通過一個完整例子來說明。通常我們使用 EventBus.getDefault() 獲取默認的 EventBus 實例,當然你也可以自己 new,但個人建議使用默認實例,以防出錯。

二、實戰演示

需求描述:點擊按鈕跳轉到第二個界面,在第二個 Activity 上點擊按鈕時向第一個 Activity 發送消息。第一個按鈕採用傳統的 Intent 方式回傳,第二個按鈕則使用 EventBus 傳遞。

1. 新建 SecondActivity 的布局(activity_two.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://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>

2. 新建事件類 FirstEvent

package com.nova.eventbus_1;
/**
 * Created by Nova on 2016/4/12.
 */
public class FirstEvent {
    private String mMsg;
    public FirstEvent(String mMsg) {
        this.mMsg = mMsg;
    }
    public String getMsg() {
        return mMsg;
    }
}

3. 在接收消息的頁面註冊 EventBus

此例中我們需要在 MainActivity 接收發回的消息,因此在 MainActivity 中進行註冊。通常我們在 onCreate() 中註冊,在 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);
        // 註冊 EventBus
        EventBus.getDefault().register(MainActivity.this);
        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();
        EventBus.getDefault().unregister(MainActivity.this);
    }
}

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. 接收消息

接收消息時,我們使用最常用的 onEventMainThread() 方法(具體為何用它,後續再詳細探討,這裡先建立初步認識,重點是先把 EventBus 跑起來)。在 MainActivity 中重寫 onEventMainThread(FirstEvent event),參數就是我們自定義的事件類:

@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());
}

收到 Event 實例後,我們把其中攜帶的消息取出,一方面用 Toast 彈出,一方面顯示到 TextView 上。

特別提醒:一定要在訂閱方法開頭寫上 @Subscribe 注解,否則會報錯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved