天天看點

Android —— EventBus使用簡介

  • EventBus有哪些優點
  • Demo案例分享及問題解決

一、什麼是EventBus

      由greenboot組織貢獻(該組織還貢獻了greenDAO),一個Android事件釋出/訂閱輕量級架構。

      EventBus可以代替Android傳統的Intent,Handler,Broadcast或接口函數,在Fragment,Activity,Service線程之間傳遞資料,執行方法。

      EventBus有五種線程模式分别是:

  1. POSTING:預設,表示事件處理函數的線程和釋出事件的線程在同一個線程。
  2. MAIN:表示事件處理函數的線程在UI主線程(不能進行耗時操作)
  3. BACKGROUND:表示事件處理函數的線程在背景線程,是以不能進行UI操作,如果釋出事件的線程是UI主線程那麼時間處理函數将會開啟一個背景線程,如果釋出事件的函數在背景線程,那麼事件處理函數就使用該線程。
  4. ASYNC:表示無論時間釋出的線程是哪一個,事件處理函數始終會建立一個子線程運作(不能進行UI操作)
  5. MAIN_ORDERED:EventBus3.1.1之後新加入的,和MAIN不同的是一定會排隊執行

二、EventBus有哪些優點?

  • 簡化了元件間的通訊。
  • 分離了事件的發送者和接受者。
  • 在Activity、Fragment和線程中表現良好。
  • 避免了複雜的和易錯的依賴關系和生命周期問題。
  • 使得代碼更簡潔,性能更好。
  • 更快,更小(約50k的jar包)。

三、Demo案例分享及問題解決

       下面用一個簡單的例子介紹一下EventBus的使用,這個例子實作的功能是:有界面1、界面2、兩個界面,界面1跳轉到界面2,界面2傳回界面1時,帶回一個參數,并且在界面1中以Toast方式展現。

  1.   添加依賴:在項目app包下的bulid.grade中添加:implementation 'org.greenrobot:eventbus:3.1.1'
Android —— EventBus使用簡介

        2.  定義事件:定義一個事件的封裝對象。在程式内部就使用該對象作為通信的資訊:    

public class FirstEvent {    private String strMsg;    public FirstEvent(String strMsg) {        this.strMsg = strMsg;
    }    public String getStrMsg() {        return strMsg;
    }
}      

         3.  注冊EventBus : 我們要在接受消息的界面注冊EventBus,界面1負責接受消息,我們将注冊EventBus的代碼放到界面1,(在onDestory中反注冊)注冊代碼:

Android —— EventBus使用簡介

        這裡一定要注意:EventBus.getDefult().resgister(this);一定要在一個public方法内,而且方法前邊一定加上注解:@Subscribe,否則會報錯:org.greenrobot.eventbus.EventBusException:

Android —— EventBus使用簡介

         4. 發送消息:使用EventBus中的Post方法來實作發送的,發送過去的是我們建立的類的執行個體(即第二步定義事件的實體類FirstEvent),發送消息在界面2,鎖一在界面2中添加代碼:

Android —— EventBus使用簡介

         注意:紅框部分一定加上,否則代碼無效

        5. 接收消息:在界面1中接收界面2傳回的消息,需要在界面1中添加代碼:

Android —— EventBus使用簡介

       完整代碼如下:界面1的xml檔案和java檔案:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView        android:id="@+id/tv_maintext"
        android:text="小朋友  你是否有很多的問号?"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <Button        android:id="@+id/btn_mainbtn"
        android:layout_width="match_parent"
        android:text="主界面"
        android:layout_height="wrap_content"/>LinearLayout>      
package com.cyf.mytestdemo;import androidx.appcompat.app.AppCompatActivity;import android.content.Intent;import android.os.Bundle;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;import org.greenrobot.eventbus.ThreadMode;public class MainActivity extends AppCompatActivity {    private Button btn_main;    private TextView tv_maintext;

    @Subscribe
    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);        //注冊該頁面為訂閱者
        EventBus.getDefault().register(this);

        btn_main=findViewById(R.id.btn_mainbtn);
        tv_maintext=findViewById(R.id.tv_maintext);

        btn_main.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {

                Intent intent=new Intent(MainActivity.this,SecondActivity.class);
                startActivity(intent);

            }
        });


    }

    @Subscribe(threadMode = ThreadMode.MAIN)    public void onEventMainThread(FirstEvent event){
        Log.e("-----", "___________________________"+event.getStrMsg());
        Toast.makeText(this,event.getStrMsg(),Toast.LENGTH_SHORT).show();
    }





    @Override    protected void onDestroy() {        super.onDestroy();        //反注冊
        EventBus.getDefault().unregister(this);
    }
}      

        界面2的xml和java檔案:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SecondActivity">

    <Button        android:id="@+id/btn_second"
        android:text="!!!!!"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>LinearLayout>      
package com.cyf.mytestdemo;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import org.greenrobot.eventbus.EventBus;public class SecondActivity extends AppCompatActivity {    private Button btn_second;

    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        btn_second=findViewById(R.id.btn_second);

        btn_second.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {

                EventBus.getDefault().post(new FirstEvent("我隻有感歎号"));
                finish();

            }
        });
    }
}      

繼續閱讀