Android —— EventBus使用簡介


參考博客:https://blog.csdn.net/harvic880925/article/details/40660137

  • 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'

        

 

 

       

        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中反注冊)注冊代碼:

        

 

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

         

 

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

         

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

 

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

        

 

 

       完整代碼如下:界面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();

            }
        });
    }
}

 

 

 

 

      


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM