淺談EventBus_Android

來源:互聯網
上載者:User

概述:

EventBus是一款針對Android最佳化的發布/訂閱事件匯流排。

主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service。

線程之間傳遞訊息.優點是開銷小,代碼更優雅,以及將寄件者和接收者解耦。

使用:

build.gradle  ,如果這種方式 不需要下載類庫或者jar包  一句話即可匯入

    compile 'de.greenrobot:eventbus:2.4.0' 

一、EventBus的使用,簡單的來說就是5步:建立一個類(具體使用下面介紹),註冊,發送訊息,接收訊息,解除註冊

看一個Demo:

實現功能:有兩個Activity,第一個Activity 跳轉第二個Activity,第二個Activity 點擊按鈕發送訊息,第一個Activity中的TextView顯示接收到的這個訊息資訊

1、寫下兩個Activity的布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"  android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"  android:paddingRight="@dimen/activity_horizontal_margin"  android:paddingTop="@dimen/activity_vertical_margin"  android:paddingBottom="@dimen/activity_vertical_margin"  android:orientation="vertical"  tools:context=".MainActivity">  <TextView    android:layout_gravity="center"    android:id="@+id/show_msg"    android:text="@string/hello_world"    android:layout_width="wrap_content"    android:layout_height="wrap_content" />  <Button    android:id="@+id/to_second_activity"    android:layout_gravity="center"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="跳轉第二個Activity"/></LinearLayout>activity_main
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  android:orientation="vertical" android:layout_width="match_parent"  android:layout_height="match_parent">  <Button    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="發送一個訊息"    android:id="@+id/send_msg" />  <Button    android:id="@+id/btn_finish"    android:text="銷毀這個Activity,返回第一個Activity"    android:layout_width="wrap_content"    android:layout_height="wrap_content" /></LinearLayout>activity_second

2、建立一個類,構造方法參數不固定,隨便寫,空類也可以,用於傳遞訊息,看具體需求

package com.xqx.com.eventbusdemo;public class MyMessage {  private String string;  public MyMessage(String string) {    this.string = string;  }  public String getString() {    return string;  }}

3、在你接收訊息的頁面(第一個Activity)註冊和解除註冊EventBus,並且擷取和處理訊息

在onCreate()方法中註冊

EventBus.getDefault().register(this);

在onDestroy()方法中取消註冊

EventBus.getDefault().unregister(this);

實現擷取處理訊息的方法,這裡先使用onEventMainThread()方法,意思為接收到訊息並在UI線程操作

public void onEventMainThread(MyMessage event) {    String msg = "onEventMainThread收到了訊息:" + event.getString();    show_msg.setText(msg);  }

完整代碼:

package com.xqx.com.eventbusdemo;import android.app.Activity;import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.TextView;import de.greenrobot.event.EventBus;public class MainActivity extends Activity {  //按鈕,開啟第二個Activity  private Button to_second_activity;  //文本,顯示接收到的訊息  private TextView show_msg;  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    to_second_activity = (Button) findViewById(R.id.to_second_activity);    show_msg = (TextView) findViewById(R.id.show_msg);    //註冊    EventBus.getDefault().register(this);    //點擊按鈕進入到第二個Activity    to_second_activity.setOnClickListener(new View.OnClickListener() {      @Override      public void onClick(View v) {        startActivity(new Intent(MainActivity.this,SecondActivity.class));      }    });  }  //接收訊息並處理  public void onEventMainThread(MyMessage event) {    String msg = "onEventMainThread收到了訊息:" + event.getString();    show_msg.setText(msg);  }  @Override  protected void onDestroy() {    super.onDestroy();    // 解除註冊    EventBus.getDefault().unregister(this);  }}MainActivity.class

4、在要發送訊息的頁面發送訊息

發送訊息很簡單,參數是你自己寫的那個類

EventBus.getDefault().post(new MyMessage("this is a message"));

完整代碼:

package com.xqx.com.eventbusdemo;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.Button;import de.greenrobot.event.EventBus;public class SecondActivity extends Activity{  private Button send_msg;  private Button btn_finish;  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_second);    send_msg = (Button) findViewById(R.id.send_msg);    btn_finish = (Button) findViewById(R.id.btn_finish);    send_msg.setOnClickListener(new View.OnClickListener() {      @Override      public void onClick(View v) {        EventBus.getDefault().post(new MyMessage("this is a message"));      }    });    btn_finish.setOnClickListener(new View.OnClickListener() {      @Override      public void onClick(View v) {        finish();      }    });  }}SecondActivity.class

 EventBus其他知識說明:

1、EventBus有四個不同的訊息接收處理方法:

onEvent:使用onEvent,那麼該事件在哪個線程發布出來的,onEvent就會在這個線程中運行,也就是說發布事件和接收事件線程在同一個線程。使用這個方法時,在onEvent方法中不能執行耗時操作,如果執行耗時操作容易導致事件分發延遲。onEventMainThread:使用onEventMainThread,那麼不論事件是在哪個線程中發布出來的,onEventMainThread都會在UI線程中執行,接收事件就會在UI線程中運行,這個在Android中是非常有用的,因為在Android中只能在UI線程中跟新UI,所以在onEvnetMainThread方法中是不能執行耗時操作的。onEventBackground:使用onEventBackgrond,那麼如果事件是在UI線程中發布出來的,那麼onEventBackground就會在子線程中運行,如果事件本來就是子線程中發布出來的,那麼onEventBackground函數直接在該子線程中執行。onEventAsync:使用onEventAsync,那麼無論事件在哪個線程發布,都會建立新的子線程在執行onEventAsync.

2、如果有多個地方發送訊息,並且有多個訊息處理函數,怎麼確定哪個訊息處理方法處理哪些訊息呢?

這就看四個訊息處理方法的參數。發送訊息的參數是某一個類,接收的也必須是這個類,否則接收不到。如有有多個OnEvent()方法參數相同,那麼這些方法都可以接收到訊息。

---------------------------------------------------------------------------------------

總結:

register(註冊)會把當前類中匹配的方法(onEvent開頭的),存入一個map,而post會根據實參去map尋找進行反射調用

以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的協助,如果有疑問大家可以留言交流,同時也希望多多支援雲棲社區!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.