EventBus使用詳解

、概述

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. }  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章