前言:第一篇文章,EventBus很多項目都在用,本文參照http://blog.csdn.net/harvic880925/article/details/40660137,自己做了一遍。把有用的挑揀出來,記錄一下啊 一、概述 EventBus是一款針對Android優化的發佈/訂閱事件匯流排。主要 ...
前言:第一篇文章,EventBus很多項目都在用,本文參照http://blog.csdn.net/harvic880925/article/details/40660137,自己做了一遍。把有用的挑揀出來,記錄一下啊
一、概述
EventBus是一款針對Android優化的發佈/訂閱事件匯流排。主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,線程之間傳遞消息.優點是開銷小,代碼更優雅。以及將發送者和接收者解耦。
1、下載EventBus的類庫
源碼:https://github.com/greenrobot/EventBus
2、基本使用
(1)自定義一個類,可以是空類,比如:
public class AnyEventType { public AnyEventType(){} }
(2)在要接收消息的頁面註冊:
eventBus.register(this);
(3)發送消息
eventBus.post(new AnyEventType event);
(4)接受消息的頁面實現(共有四個函數,各功能不同):
public void onEvent(AnyEventType event) {} public void onEventMainThread(AnyEventType event) {} public void onEventBackgroundThread(AnyEventType event) {} public void onEventAsync(AnyEventType event) {}
onEvent:如果使用onEvent作為訂閱函數,那麼該事件在哪個線程發佈出來的,onEvent就會在這個線程中運行,也就是說發佈事件和接收事件線程在同一個線程。使用這個方法時,在onEvent方法中不能執行耗時操作,如果執行耗時操作容易導致事件分發延遲。
onEventMainThread:如果使用onEventMainThread作為訂閱函數,那麼不論事件是在哪個線程中發佈出來的,onEventMainThread都會在UI線程中執行,接收事件就會在UI線程中運行,這個在Android中是非常有用的,因為在Android中只能在UI線程中跟新UI,所以在onEvnetMainThread方法中是不能執行耗時操作的。
onEventBackground:如果使用onEventBackgrond作為訂閱函數,那麼如果事件是在UI線程中發佈出來的,那麼onEventBackground就會在子線程中運行,如果事件本來就是子線程中發佈出來的,那麼onEventBackground函數直接在該子線程中執行。
onEventAsync:使用這個函數作為訂閱函數,那麼無論事件在哪個線程發佈,都會創建新的子線程在執行onEventAsync.
(5)解除註冊
eventBus.unregister(this);
順序就是這麼個順序,可真正讓自己寫,估計還是雲里霧裡的,下麵舉個例子來說明下。
首先,在EventBus中,獲取實例的方法一般是採用EventBus.getInstance()來獲取預設的EventBus實例,當然你也可以new一個又一個,個人感覺還是用預設的比較好,以防出錯。
二、實戰
先給大家看個例子:
當擊跳轉到第二個界面按鈕的時候,跳到第二個Activity,當點擊第二個activity上面的t按鈕的時候向第一個Activity發送消息,第一個按鈕使用的是
新建一個Activity,SecondActivity佈局(activity_two.xml)
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 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"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/bt_text_post" android:id="@+id/bt_post"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/bt_text_post2" android:layout_below="@id/bt_post" android:id="@+id/bt_post2"/> </RelativeLayout>
MainActivity.java
package com.nova.eventbus_1; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; 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; public class MainActivity extends AppCompatActivity { private Button button_jump; private TextView tv_notify; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button_jump= (Button) findViewById(R.id.bt_jump); tv_notify= (TextView) findViewById(R.id.tv_notify); button_jump.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { <strong> Intent intent=new Intent(MainActivity.this,SecondActivity.class); startActivityForResult(intent,1);</strong> } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode){ case 1: if(resultCode==1){ String returnedData=data.getStringExtra("com.nova.eventbus_1.data_return"); tv_notify.setText(returnedData); Toast.makeText(MainActivity.this,returnedData,Toast.LENGTH_LONG).show(); Log.i("現在的線程",Thread.currentThread().getName()); } } } }
SecondActivity.java
package com.nova.eventbus_1; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import org.greenrobot.eventbus.EventBus; /** * Created by Nova on 2016/4/11. */ public class SecondActivity extends AppCompatActivity { private Button button_post; private Button button_post2;//使用EventBus傳遞 @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_two); button_post= (Button) findViewById(R.id.bt_post); button_post2= (Button) findViewById(R.id.bt_post2); button_post.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(); intent.putExtra("com.nova.eventbus_1.data_return","跳轉按鈕:被點擊了"); setResult(1,intent); finish(); } }); } }
2、新建一個類FirstEvent
package com.nova.eventbus_1; /** * Created by Nova on 2016/4/12. * [email protected] */ public class FirstEvent { private String mMsg; public FirstEvent(String mMsg) { this.mMsg = mMsg; } public String getMsg() { return mMsg; } }
3、在要接收消息的頁面註冊EventBus:
在上面的GIF圖片的演示中,大家也可以看到,我們是要在MainActivity中接收發過來的消息的,所以我們在MainActivity中註冊消息。
通過我們會在OnCreate()函數中註冊EventBus,在OnDestroy()函數中反註冊。所以整體的註冊與反註冊的代碼如下:
package com.nova.eventbus_1; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; 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; public class MainActivity extends AppCompatActivity { private Button button_jump; private TextView tv_notify; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); <strong> //註冊EventBus EventBus.getDefault().register(MainActivity.this);</strong> button_jump= (Button) findViewById(R.id.bt_jump); tv_notify= (TextView) findViewById(R.id.tv_notify); button_jump.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(MainActivity.this,SecondActivity.class); startActivityForResult(intent,1); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode){ case 1: if(resultCode==1){ String returnedData=data.getStringExtra("com.nova.eventbus_1.data_return"); tv_notify.setText(returnedData); Toast.makeText(MainActivity.this,returnedData,Toast.LENGTH_LONG).show(); Log.i("現在的線程",Thread.currentThread().getName()); } } } @Subscribe public void onEventMainThread(FirstEvent event){ String msg="onEventMainThread收到了消息:" + event.getMsg(); tv_notify.setText(msg); Toast.makeText(MainActivity.this,msg,Toast.LENGTH_LONG).show(); Log.i("現在的線程",Thread.currentThread().getName()); } @Override protected void onDestroy() { super.onDestroy(); <strong>EventBus.getDefault().unregister(MainActivity.this);</strong> } }
4、發送消息
發送消息是使用EventBus中的Post方法來實現發送的,發送過去的是我們新建的類的實例!
EventBus.getDefault().post(new FirstEvent("跳轉按鈕:被點擊了EventBus post"));
完整的SecondActivity.java的代碼如下:
package com.nova.eventbus_1; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import org.greenrobot.eventbus.EventBus; /** * Created by Nova on 2016/4/11. */ public class SecondActivity extends AppCompatActivity { private Button button_post; private Button button_post2;//使用EventBus傳遞 @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_two); button_post= (Button) findViewById(R.id.bt_post); button_post2= (Button) findViewById(R.id.bt_post2); button_post.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(); intent.putExtra("com.nova.eventbus_1.data_return","跳轉按鈕:被點擊了"); setResult(1,intent); finish(); } }); button_post2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //EventBus使用方法 EventBus.getDefault().post(new FirstEvent("跳轉按鈕:被點擊了EventBus post")); finish(); } }); } }
5、接收消息
接收消息時,我們使用EventBus中最常用的onEventMainThread()函數來接收消息,具體為什麼用這個,我們下篇再講,這裡先給大家一個初步認識,要先能把EventBus用起來先。
在MainActivity中重寫onEventMainThread(FirstEvent event),參數就是我們自己定義的類:
在收到Event實例後,我們將其中攜帶的消息取出,一方面Toast出去,一方面傳到TextView中;
@Subscribe public void onEventMainThread(FirstEvent event){ String msg="onEventMainThread收到了消息:" + event.getMsg(); tv_notify.setText(msg); Toast.makeText(MainActivity.this,msg,Toast.LENGTH_LONG).show(); Log.i("現在的線程",Thread.currentThread().getName()); }
切記一定在開頭寫上@Subscribe,不然報錯。
程式結束。