android事件總線EventBus3.0使用方法詳解
一.EventBus概述
1.EventBus的三要素
EventBus有三個主要的元素需要我們先了解一下:
Event:事件,可以是任意類型的對象。
Subscriber:事件訂閱者,在EventBus3.0之前消息處理的方法只能限定于onEvent、onEventMainThread、onEventBackgroundThread和onEventAsync,他們分別代表四種線程模型。而在EventBus3.0之后,事件處理的方法可以隨便取名,但是需要添加一個注解@Subscribe,并且要指定線程模型(默認(rèn)為POSTING),四種線程模型下面會講到。
Publisher:事件發(fā)布者,可以在任意線程任意位置發(fā)送事件,直接調(diào)用EventBus的post(Object)方法??梢宰约簩嵗疎ventBus對象,但一般使用EventBus.getDefault()就好了,根據(jù)post函數(shù)參數(shù)的類型,會自動調(diào)用訂閱相應(yīng)類型事件的函數(shù)。
2.EventBus的四種ThreadMode(線程模型)
EventBus3.0有以下四種ThreadMode:
POSTING(默認(rèn)):如果使用事件處理函數(shù)指定了線程模型為POSTING,那么該事件在哪個線程發(fā)布出來的,事件處理函數(shù)就會在這個線程中運行,也就是說發(fā)布事件和接收事件在同一個線程。在線程模型為POSTING的事件處理函數(shù)中盡量避免執(zhí)行耗時操作,因為它會阻塞事件的傳遞,甚至有可能會引起ANR。
MAIN:事件的處理會在UI線程中執(zhí)行。事件處理時間不能太長,長了會ANR的。
BACKGROUND:如果事件是在UI線程中發(fā)布出來的,那么該事件處理函數(shù)就會在新的線程中運行,如果事件本來就是子線程中發(fā)布出來的,那么該事件處理函數(shù)直接在發(fā)布事件的線程中執(zhí)行。在此事件處理函數(shù)中禁止進行UI更新操作。
ASYNC:無論事件在哪個線程發(fā)布,該事件處理函數(shù)都會在新建的子線程中執(zhí)行,同樣,此事件處理函數(shù)中禁止進行UI更新操作。
二.EventBus的基本用法
1.自定義一個事件類(相當(dāng)于我們平常所用的bean類)
public class MessageEvent {
...
}
2.在需要訂閱的地方注冊
EventBus.getDefault().register(this);
3.發(fā)送事件
第一種.普通事件
EventBus.getDefault().post(messageEvent);
第二種.粘性事件
EventBus.getDefault().postSticky(messageEvent);
4.處理事件(eg.刷新UI)
@Subscribe(threadMode = ThreadMode.MAIN)
public void XXX(MessageEvent messageEvent) {
...
}
5.取消事件訂閱
@Override
protected void onDestroy() {
EventBus.getDefault().unregister(this);
super.onDestroy();
}
三.EventBus的實際應(yīng)用(模擬登陸傳值)

1.導(dǎo)入3.0依賴
compile 'org.greenrobot:eventbus:3.0.0'
2.定義消息事件類
public class MessageEvent {
public final String uname;
public final String upass;
public MessageEvent(String name,String pass) {
this.uname = name;
this.upass = pass;
}
}
3.發(fā)送事件(粘性事件)
public class MainActivity extends AppCompatActivity {
private String username;
private String password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextInputLayout usernameWrapper = (TextInputLayout) findViewById(R.id.usernameWrapper);
final TextInputLayout passwordWrapper = (TextInputLayout) findViewById(R.id.passwordWrapper);
Button btn = (Button) findViewById(R.id.btn);
usernameWrapper.setHint("請輸入賬號");
passwordWrapper.setHint("請輸入密碼");
//點擊事件
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hideKeyboard();
username = usernameWrapper.getEditText().getText().toString();
password = passwordWrapper.getEditText().getText().toString();
if (!validateEmail(username)) {
usernameWrapper.setError("Not a valid email address!");
} else if (!validatePassword(password)) {
passwordWrapper.setError("Not a valid password!");
} else {
usernameWrapper.setErrorEnabled(false);
passwordWrapper.setErrorEnabled(false);
//發(fā)送粘性事件//////////////////
EventBus.getDefault().postSticky(new MessageEvent(username,password));
startActivity(new Intent(MainActivity.this,SecondActivity.class));
}
}
});
}
private void hideKeyboard() {
View view = getCurrentFocus();
if (view != null) {
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).
hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
//郵箱驗證
public boolean validateEmail(String email) {
return email.length() > 5;
}
// 密碼驗證
public boolean validatePassword(String password) {
return password.length() > 5;
}
}
4.注冊和取消訂閱事件
public class SecondActivity extends AppCompatActivity {
private TextView name,pass;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
name= (TextView) findViewById(R.id.uname);
pass= (TextView) findViewById(R.id.upass);
button= (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//注冊EventBus
EventBus.getDefault().register(SecondActivity.this);
}
});
}
//事件訂閱者處理事件
@Subscribe(threadMode = ThreadMode.POSTING,sticky = true)
public void onUserEvent(MessageEvent event) {
name.setText("用戶名:" + event.uname);
pass.setText("用戶名:" + event.upass);
}
//取消注冊
@Override
protected void onDestroy() {
EventBus.getDefault().unregister(this);
super.onDestroy();
}
}
布局
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:text="Welcome"
android:textSize="30sp"
android:textColor="#333333"/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:id="@+id/usernameWrapper"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:hint="Username"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/passwordWrapper"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/usernameWrapper"
android:layout_marginTop="4dp">
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="Password"/>
</android.support.design.widget.TextInputLayout>
<Button
android:id="@+id/btn"
android:layout_marginTop="4dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"/>
</LinearLayout>
</LinearLayout>
activity_second.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_second" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="60dp" android:gravity="center"> <Button android:id="@+id/button" android:layout_width="100dp" android:layout_height="match_parent" android:text="接收數(shù)據(jù)" /> </LinearLayout> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/uname" android:layout_weight="1" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/upass" android:layout_weight="1" /> </LinearLayout> </LinearLayout>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android為Tiny4412設(shè)備驅(qū)動在proc目錄下添加一個可讀版本信息的文件
今天小編就為大家分享一篇關(guān)于Android為Tiny4412設(shè)備驅(qū)動在proc目錄下添加一個可讀版本信息的文件,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-12-12
Android自定義ViewGroup實現(xiàn)受邊界限制的滾動操作(3)
這篇文章主要為大家詳細(xì)介紹了Android自定義ViewGroup實現(xiàn)受邊界限制的滾動操作,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-12-12
Android 微信小視頻錄制功能實現(xiàn)詳細(xì)介紹
這篇文章主要介紹了Android 微信小視頻錄制功能實現(xiàn)詳解的相關(guān)資料,這里提供了具體的實現(xiàn)思路及代碼,需要的朋友可以參考下2016-11-11
Android實現(xiàn)打開手機淘寶并自動識別淘寶口令彈出商品信息功能
最近項目經(jīng)理給我們安排一個活兒,基于Android開發(fā)實現(xiàn)打開手機淘寶,并自動識別淘口令,彈出商品信息,今天小編就抽空給大家分享下這個需求是怎么實現(xiàn)的,需要的朋友參考下吧2017-11-11
Android BroadcastReceiver接收收到短信的廣播
這篇文章主要為大家詳細(xì)介紹了Android BroadcastReceiver接收收到短信的廣播,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-05-05
Android使用Javamail發(fā)送Email群發(fā)加附件
這篇文章主要為大家詳細(xì)介紹了Android使用Javamail發(fā)送Email群發(fā)加附件,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-01-01
Android如何實現(xiàn)動態(tài)滾動波形圖(心電圖)功能
這篇文章主要介紹了Android如何實現(xiàn)動態(tài)滾動波形圖(心電圖)功能,幫助大家更好的理解和學(xué)習(xí)使用Android,感興趣的朋友可以了解下2021-03-03

