Android之利用EventBus發(fā)送消息傳遞示例
一、概述
EventBus是一款針對(duì)Android優(yōu)化的發(fā)布/訂閱事件總線。主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,線程之間傳遞消息.優(yōu)點(diǎn)是開(kāi)銷小,代碼更優(yōu)雅。以及將發(fā)送者和接收者解耦。
1、下載EventBus的類庫(kù)
2、基本使用
(1)自定義一個(gè)類,可以是空類,比如:
public class AnyEventType {
public AnyEventType(){}
}
(2)在要接收消息的頁(yè)面注冊(cè):
eventBus.register(this);
(3)發(fā)送消息
eventBus.post(new AnyEventType event);
(4)接受消息的頁(yè)面實(shí)現(xiàn)(共有四個(gè)函數(shù),各功能不同,這是其中之一,可以選擇性的實(shí)現(xiàn),這里先實(shí)現(xiàn)一個(gè)):
public void onEvent(AnyEventType event) {}
(5)解除注冊(cè)
eventBus.unregister(this);
順序就是這么個(gè)順序,可真正讓自己寫(xiě),估計(jì)還是云里霧里的,下面舉個(gè)例子來(lái)說(shuō)明下。
首先,在EventBus中,獲取實(shí)例的方法一般是采用EventBus.getInstance()來(lái)獲取默認(rèn)的EventBus實(shí)例,當(dāng)然你也可以new一個(gè)又一個(gè),個(gè)人感覺(jué)還是用默認(rèn)的比較好,以防出錯(cuò)。
二、實(shí)戰(zhàn)
先給大家看個(gè)例子:
當(dāng)擊btn_try按鈕的時(shí)候,跳到第二個(gè)Activity,當(dāng)點(diǎn)擊第二個(gè)activity上面的First Event按鈕的時(shí)候向第一個(gè)Activity發(fā)送消息,當(dāng)?shù)谝粋€(gè)Activity收到消息后,一方面將消息Toast顯示,一方面放入textView中顯示。

按照下面的步驟,下面來(lái)建這個(gè)工程:
1、基本框架搭建
想必大家從一個(gè)Activity跳轉(zhuǎn)到第二個(gè)Activity的程序應(yīng)該都會(huì)寫(xiě),這里先稍稍把兩個(gè)Activity跳轉(zhuǎn)的代碼建起來(lái)。后面再添加EventBus相關(guān)的玩意。
MainActivity布局(activity_main.xml)
<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:orientation="vertical"> <Button android:id="@+id/btn_try" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="btn_bty"/> <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="match_parent"/> </LinearLayout>
新建一個(gè)Activity,SecondActivity布局(activity_second.xml)
<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:orientation="vertical" tools:context="com.harvic.try_eventbus_1.SecondActivity" > <Button android:id="@+id/btn_first_event" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="First Event"/> </LinearLayout>
MainActivity.java (點(diǎn)擊btn跳轉(zhuǎn)到第二個(gè)Activity)
public class MainActivity extends Activity {
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn_try);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
startActivity(intent);
}
});
}
}
到這,基本框架就搭完了,下面開(kāi)始按步驟使用EventBus了。
2、新建一個(gè)類FirstEvent
package com.harvic.other;
public class FirstEvent {
private String mMsg;
public FirstEvent(String msg) {
// TODO Auto-generated constructor stub
mMsg = msg;
}
public String getMsg(){
return mMsg;
}
}
這個(gè)類很簡(jiǎn)單,構(gòu)造時(shí)傳進(jìn)去一個(gè)字符串,然后可以通過(guò)getMsg()獲取出來(lái)。
3、在要接收消息的頁(yè)面注冊(cè)EventBus:
在上面的GIF圖片的演示中,大家也可以看到,我們是要在MainActivity中接收發(fā)過(guò)來(lái)的消息的,所以我們?cè)贛ainActivity中注冊(cè)消息。
通過(guò)我們會(huì)在OnCreate()函數(shù)中注冊(cè)EventBus,在OnDestroy()函數(shù)中反注冊(cè)。所以整體的注冊(cè)與反注冊(cè)的代碼如下:
package com.example.tryeventbus_simple;
import com.harvic.other.FirstEvent;
import de.greenrobot.event.EventBus;
import android.app.Activity;
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;
public class MainActivity extends Activity {
Button btn;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//注冊(cè)EventBus
EventBus.getDefault().register(this);
btn = (Button) findViewById(R.id.btn_try);
tv = (TextView)findViewById(R.id.tv);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
startActivity(intent);
}
});
}
@Override
protected void onDestroy(){
super.onDestroy();
EventBus.getDefault().unregister(this);//反注冊(cè)EventBus
}
}
4、發(fā)送消息
發(fā)送消息是使用EventBus中的Post方法來(lái)實(shí)現(xiàn)發(fā)送的,發(fā)送過(guò)去的是我們新建的類的實(shí)例!
EventBus.getDefault().post(new FirstEvent("FirstEvent btn clicked"));
完整的SecondActivity.Java的代碼如下:
package com.example.tryeventbus_simple;
import com.harvic.other.FirstEvent;
import de.greenrobot.event.EventBus;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class SecondActivity extends Activity {
private Button btn_FirstEvent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
btn_FirstEvent = (Button) findViewById(R.id.btn_first_event);
btn_FirstEvent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
EventBus.getDefault().post(
new FirstEvent("FirstEvent btn clicked"));
}
});
}
}
5、接收消息
接收消息時(shí),我們使用EventBus中最常用的onEventMainThread()函數(shù)來(lái)接收消息,具體為什么用這個(gè),我們下篇再講,這里先給大家一個(gè)初步認(rèn)識(shí),要先能把EventBus用起來(lái)先。
在MainActivity中重寫(xiě)onEventMainThread(FirstEvent event),參數(shù)就是我們自己定義的類:
在收到Event實(shí)例后,我們將其中攜帶的消息取出,一方面Toast出去,一方面?zhèn)鞯絋extView中;
public void onEventMainThread(FirstEvent event) {
String msg = "onEventMainThread收到了消息:" + event.getMsg();
Log.d("harvic", msg);
tv.setText(msg);
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
完整的MainActiviy代碼如下:
package com.example.tryeventbus_simple;
import com.harvic.other.FirstEvent;
import de.greenrobot.event.EventBus;
import android.app.Activity;
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;
public class MainActivity extends Activity {
Button btn;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(this);
btn = (Button) findViewById(R.id.btn_try);
tv = (TextView)findViewById(R.id.tv);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
startActivity(intent);
}
});
}
public void onEventMainThread(FirstEvent event) {
String msg = "onEventMainThread收到了消息:" + event.getMsg();
Log.d("harvic", msg);
tv.setText(msg);
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
@Override
protected void onDestroy(){
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}
好了,到這,基本上算初步把EventBus用起來(lái)了,下篇再講講EventBus的幾個(gè)函數(shù),及各個(gè)函數(shù)間是如何識(shí)別當(dāng)前如何調(diào)用哪個(gè)函數(shù)的。
源碼地址:EventBus_jb51.rar
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- vue2+elementUI的el-tree的懶加載功能
- vue2+elementUI的el-tree的選中、高亮、定位功能的實(shí)現(xiàn)
- Element-ui樹(shù)形控件el-tree自定義增刪改和局部刷新及懶加載操作
- ElementUI中el-tree節(jié)點(diǎn)的操作的實(shí)現(xiàn)
- 解決Vue使用bus總線時(shí),第一次路由跳轉(zhuǎn)時(shí)數(shù)據(jù)沒(méi)成功傳遞問(wèn)題
- Vue EventBus自定義組件事件傳遞
- element UI 中的 el-tree 實(shí)現(xiàn) checkbox 單選框及 bus 傳遞參數(shù)功能
相關(guān)文章
Android 集成Google Cast 異常問(wèn)題解析
這篇文章主要為大家介紹了Android 集成Google Cast 異常問(wèn)題解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02
解決Android從相冊(cè)中獲取圖片出錯(cuò)圖片卻無(wú)法裁剪問(wèn)題的方法
這篇文章主要介紹了解決Android從相冊(cè)中獲取圖片出錯(cuò)圖片卻無(wú)法裁剪問(wèn)題的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-01-01
Android仿活動(dòng)時(shí)分秒倒計(jì)時(shí)效果
這篇文章主要為大家詳細(xì)介紹了Android仿活動(dòng)時(shí)分秒倒計(jì)時(shí)效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-02-02
Android仿支付寶自定義密碼輸入框及安全鍵盤(密碼鍵盤)
這篇文章主要介紹了Android仿支付寶自定義密碼輸入框及安全鍵盤(密碼鍵盤),需要的朋友可以參考下2018-01-01
根據(jù)USER-AGENT判斷手機(jī)類型并跳轉(zhuǎn)到相應(yīng)的app下載頁(yè)面
檢測(cè)瀏覽器的USER-AGENT,然后根據(jù)正則表達(dá)式來(lái)確定客戶端類型,并跳轉(zhuǎn)到相應(yīng)的app下載頁(yè)面,這個(gè)方法還是比較實(shí)用的,大家可以看看2014-09-09
Android 利用ViewPager+GridView實(shí)現(xiàn)首頁(yè)導(dǎo)航欄布局分頁(yè)效果
用ViewPager+GridView實(shí)現(xiàn)首頁(yè)導(dǎo)航欄布局分頁(yè)效果來(lái)實(shí)現(xiàn)的效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2016-10-10
Android中imageview.ScaleType使用方法詳細(xì)介紹
這篇文章主要介紹了Android中imageview.ScaleType使用方法詳細(xì)介紹的相關(guān)資料,需要的朋友可以參考下2017-06-06
Android下拉刷新PtrFrameLayout的使用實(shí)例代碼
本篇文章主要介紹了Android下拉刷新PtrFrameLayout的使用實(shí)例代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06
Android編程實(shí)現(xiàn)文字倒影效果的方法
這篇文章主要介紹了Android編程實(shí)現(xiàn)文字倒影效果的方法,涉及Android布局與圖形繪制相關(guān)操作技巧,需要的朋友可以參考下2017-03-03

