EventBus使用介紹

来源:https://www.cnblogs.com/qynprime/archive/2018/01/22/8329380.html
-Advertisement-
Play Games

本文出自:http://blog.csdn.net/harvic880925/article/details/40660137 源碼地址:http://download.csdn.net/detail/harvic880925/8111357 一、概述 EventBus是一款針對Android優化的 ...


本文出自:http://blog.csdn.net/harvic880925/article/details/40660137

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

一、概述

EventBus是一款針對Android優化的發佈/訂閱事件匯流排。主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,線程之間傳遞消息.優點是開銷小,代碼更優雅。以及將發送者和接收者解耦。
1、下載EventBus的類庫
源碼:https://github.com/greenrobot/EventBus

2、基本使用

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

 

[java] view plain copy  
  1. public class AnyEventType {  
  2.      public AnyEventType(){}  
  3.  }  

 

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

 

[java] view plain copy  
  1. eventBus.register(this);  

 

(3)發送消息

 

[java] view plain copy  
  1. eventBus.post(new AnyEventType event);  

(4)接受消息的頁面實現(共有四個函數,各功能不同,這是其中之一,可以選擇性的實現,這裡先實現一個):

 

[java] view plain copy  
  1. public void onEvent(AnyEventType event) {}  

(5)解除註冊

[java] view plain copy  
  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)

 

[html] view plain copy  
  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.       
  7.     <Button   
  8.         android:id="@+id/btn_try"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:text="btn_bty"/>  
  12.     <TextView   
  13.         android:id="@+id/tv"  
  14.         android:layout_width="wrap_content"  
  15.         android:layout_height="match_parent"/>  
  16.   
  17. </LinearLayout>  

新建一個Activity,SecondActivity佈局(activity_second.xml)

[html] view plain copy  
  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.   
  8.     <Button   
  9.         android:id="@+id/btn_first_event"  
  10.         android:layout_width="match_parent"  
  11.         android:layout_height="wrap_content"  
  12.         android:text="First Event"/>  
  13.   
  14. </LinearLayout>  

MainActivity.java (點擊btn跳轉到第二個Activity)

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

到這,基本框架就搭完了,下麵開始按步驟使用EventBus了。

2、新建一個類FirstEvent

 

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

這個類很簡單,構造時傳進去一個字元串,然後可以通過getMsg()獲取出來。

 

3、在要接收消息的頁面註冊EventBus:

在上面的GIF圖片的演示中,大家也可以看到,我們是要在MainActivity中接收發過來的消息的,所以我們在MainActivity中註冊消息。

通過我們會在OnCreate()函數中註冊EventBus,在OnDestroy()函數中反註冊。所以整體的註冊與反註冊的代碼如下:

 

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

4、發送消息

發送消息是使用EventBus中的Post方法來實現發送的,發送過去的是我們新建的類的實例!

 

[java] view plain copy  
  1. EventBus.getDefault().post(new FirstEvent("FirstEvent btn clicked"));  

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

 

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

5、接收消息

接收消息時,我們使用EventBus中最常用的onEventMainThread()函數來接收消息,具體為什麼用這個,我們下篇再講,這裡先給大家一個初步認識,要先能把EventBus用起來先。

 

在MainActivity中重寫onEventMainThread(FirstEvent event),參數就是我們自己定義的類:

在收到Event實例後,我們將其中攜帶的消息取出,一方面Toast出去,一方面傳到TextView中;

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

完整的MainActiviy代碼如下:

 

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

好了,到這,基本上算初步把EventBus用起來了,下篇再講講EventBus的幾個函數,及各個函數間是如何識別當前如何調用哪個函數的。

添加依賴庫

Android Studio 配置gradle:

compile 'org.greenrobot:eventbus:3.0.0'


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1.Redis簡介 Redis 是一個開源(BSD許可)的,記憶體中的數據結構存儲系統,它可以用作資料庫、緩存和消息中間件。 它支持多種類型的數據結構,如 字元串(strings), 散列(hashes), 列表(lists), 集合(sets), 有序集合(sorted sets) 與範圍查詢, b ...
  • 本文是對自己學習過程的一個記錄和彙總,作為自己的一個總結性的文檔,並隨著進度更新完善。作為一個初學者,文章若有不妥之處還請各位讀者提出來,大家共同交流進步,謝謝! OSM地圖數據下載: osm是一個開放式線上地圖平臺,Open Street Map(簡稱 OSM)是一個存儲海量XML 數據的資料庫( ...
  • 1、關係的集合運算 集合的3個最普通的運算是並、交和差。對於任意集合R和S(當然,這裡的R和S可以是表R和表S),這些運算定義如下。 R並S,R或S或兩者中元素的集合。一個元素在並集中只出現一次,即使它在R和S中都存在。 R交S,R和S中都存在的元素的集合。 R差S,在R中而不在S中的元素的集合。註 ...
  • 資料庫存放數據的文件,本文稱其為data file。 資料庫的內容在記憶體里是有緩存的,這裡命名為db buffer。某次操作,我們取了資料庫某表格中的數據,這個數據會在記憶體中緩存一些時間。對這個數據的修改在開始時候也只是修改在記憶體中的內容。當db buffer已滿或者遇到其他的情況,這些數據會寫入d ...
  • 2006年google技術人員Fay Chang發佈了一篇文章《Bigtable: A Distributed Storage System for Structured Data》。該文章向世人介紹了一種分散式的資料庫,這種資料庫可以在局部幾台伺服器崩潰的情況下繼續提供高性能的服務。 2007年P ...
  • 在開發項目之前,我們需要做一些準備工作,瞭解iOS擴展——Objective-C開發編程規範是進行開發的必備基礎,學習iOS學習——Xcode9上傳項目到GitHub是我們進行版本控制和代碼管理的選擇之一,明白iOS學習——iOS項目Project 和 Targets配置詳解則更利於我們今天對完整項 ...
  • 一、不自動彈出鍵盤: 帶有EditText控制項的在第一次顯示的時候會自動獲得focus,並彈出鍵盤,如果不想自動彈出鍵盤,有兩種方法: 方法一:在mainfest文件中把對應的activity設置 android:windowSoftInputMode="stateHidden" 或者android ...
  • 0、寫在前面 1、小技巧 UILabel類: 1-1-1)、設置行間距富文本,有省略號要求的,需要再次設置省略(初始化時設置的會失效)。 UITextField類: 1-2-1)、清空按鈕。 UITextView類: 1-3-1)、UITextView只能x軸居中,y軸需要手動調。 UITextFi ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...