【EventBus】发布-订阅模式 ( Android 中使用 发布-订阅模式 进行通信 )
文章目錄
- 一、拷貝 發布-訂閱模式 相關類
- 二、完整代碼示例
一、拷貝 發布-訂閱模式 相關類
將上一篇博客 【EventBus】發布-訂閱模式 ( 使用代碼實現發布-訂閱模式 ) 寫的 發布-訂閱模式 相關代碼拷貝到Android Studio 工程中 ,
在 Android 中 , 將 Activity 定義成訂閱者 , 訂閱者需要實現 Subscriber 接口 , 實現 public void onEvent(String msg) 接口方法 , 接收到消息后 , Toast 消息即可 ;
public class MainActivity2 extends AppCompatActivity implements Subscriber {@Overridepublic void onEvent(String msg) {Toast.makeText(this,"訂閱者 Activity 接收到消息 : " + msg,Toast.LENGTH_LONG).show();} }在 Activity 的 onCreate 方法中 , 將訂閱者 Subscriber 注冊到 調度中心 Dispatcher ;
@Overrideprotected void onCreate(Bundle savedInstanceState) {// 注冊訂閱者Dispatcher.getInstance().register(this);}在 Activity 的 onDestory 方法中 , 將訂閱者 Subscriber 從 調度中心 Dispatcher 中取消注冊 ;
@Overrideprotected void onDestroy() {// 取消注冊訂閱者Dispatcher.getInstance().unregister(this);}使用 Activity 中的按鈕點擊事件觸發 發布者 Publisher 向調度中心發布消息 ;
textView = findViewById(R.id.textView);// 設置點擊事件, 點擊后發送消息textView.setOnClickListener((View view)->{// 發布者發布消息new Publisher().post("Hello");});訂閱者 Activity 接收到消息后 , 將消息 Toast 出來 ;
EventBus 也是以該 發布-訂閱模式 為核心開發的 ;
二、完整代碼示例
發布者 , 訂閱者 , 調度中心 的 代碼 , 與 【EventBus】發布-訂閱模式 ( 使用代碼實現發布-訂閱模式 ) 博客中的一致 , 直接將這些代碼拷貝到 Android Studio 工程中 , 這里就不再重復粘貼了 ;
Activity 作為訂閱者完整代碼 :
package com.eventbus_demo;import android.os.Bundle; import android.view.View; import android.widget.TextView; import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import com.eventbus_demo.publisher_subscriber.Dispatcher; import com.eventbus_demo.publisher_subscriber.Publisher; import com.eventbus_demo.publisher_subscriber.Subscriber;public class MainActivity2 extends AppCompatActivity implements Subscriber {private TextView textView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);textView = findViewById(R.id.textView);// 設置點擊事件, 點擊后發送消息textView.setOnClickListener((View view)->{// 發布者發布消息new Publisher().post("Hello");});// 注冊訂閱者Dispatcher.getInstance().register(this);}@Overrideprotected void onDestroy() {super.onDestroy();// 取消注冊訂閱者Dispatcher.getInstance().unregister(this);}@Overridepublic void onEvent(String msg) {Toast.makeText(this,"訂閱者 Activity 接收到消息 : " + msg,Toast.LENGTH_LONG).show();} }執行結果 : 點擊按鈕 , 發布者發送 “Hello” 消息給訂閱者 MainActivity2 , 訂閱者收到消息后 , Toast 消息內容 ;
總結
以上是生活随笔為你收集整理的【EventBus】发布-订阅模式 ( Android 中使用 发布-订阅模式 进行通信 )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【开发环境】Windows 系统中使用
- 下一篇: 【EventBus】EventBus 源