一.EventBus概述
1.EventBus的三要素
EventBus有三個主要的元素需要我們先了解一下:
	Event:事件,可以是任意類型的對象。
	Subscriber:事件訂閱者,在EventBus3.0之前消息處理的方法只能限定于onEvent、onEventMainThread、onEventBackgroundThread和onEventAsync,他們分別代表四種線程模型。而在EventBus3.0之后,事件處理的方法可以隨便取名,但是需要添加一個注解@Subscribe,并且要指定線程模型(默認為POSTING),四種線程模型下面會講到。
	Publisher:事件發布者,可以在任意線程任意位置發送事件,直接調用EventBus的post(Object)方法。可以自己實例化EventBus對象,但一般使用EventBus.getDefault()就好了,根據post函數參數的類型,會自動調用訂閱相應類型事件的函數。
2.EventBus的四種ThreadMode(線程模型)
EventBus3.0有以下四種ThreadMode:
	POSTING(默認):如果使用事件處理函數指定了線程模型為POSTING,那么該事件在哪個線程發布出來的,事件處理函數就會在這個線程中運行,也就是說發布事件和接收事件在同一個線程。在線程模型為POSTING的事件處理函數中盡量避免執行耗時操作,因為它會阻塞事件的傳遞,甚至有可能會引起ANR。
	MAIN:事件的處理會在UI線程中執行。事件處理時間不能太長,長了會ANR的。
	BACKGROUND:如果事件是在UI線程中發布出來的,那么該事件處理函數就會在新的線程中運行,如果事件本來就是子線程中發布出來的,那么該事件處理函數直接在發布事件的線程中執行。在此事件處理函數中禁止進行UI更新操作。
	ASYNC:無論事件在哪個線程發布,該事件處理函數都會在新建的子線程中執行,同樣,此事件處理函數中禁止進行UI更新操作。
二.EventBus的基本用法
1.自定義一個事件類(相當于我們平常所用的bean類)
public class MessageEvent { ...}2.在需要訂閱的地方注冊
EventBus.getDefault().register(this);
3.發送事件
	第一種.普通事件
	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的實際應用(模擬登陸傳值)
	
1.導入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.發送事件(粘性事件)
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);     //發送粘性事件//////////////////     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="接收數據" /> </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>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答