簡體   English   中英

android EventBus 作為 LocalBroadcastManager 的替代品

[英]android EventBus as LocalBroadcastManager replacement

建議使用 greenrobot EventBus 替代(現已棄用)LocalBroadcastManager。 我目前正在使用 LocalBroadcastManager 將意圖從服務發送到 MainActivity,如下所示:

val intent = Intent("service event")
intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
intent.putExtra("param", "some value")
LocalBroadcastManager.getInstance(this).sendBroadcast(intent)

這將清除堆棧,並且 MainActivity 作為堆棧中的唯一活動變得可見。

發布 EventBus 事件時,如何實現相同的( Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP )效果?

經過一些實驗,我找到了一個“解決方案”:

  1. 在 MainActivity EventBus.getDefault().register(this)onCreate()中注冊 EventBus。 這使得 MainActivity 可以接收帖子,即使它不在活動堆棧的頂部。 然后,當然,在onDestroy()中取消注冊。
  2. 在 MainActivity 事件接收器 function 中,使用Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP標志再次啟動 MainActivity,例如:
    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onEventReceived(event: BusEvent) {
        val i = Intent(applicationContext, MainActivity::class.java)
        i.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
        i.putExtra("action", event.action)
        i.putExtra("params", event.params)
        startActivity(i)
    }

我對此並不陌生,我們很感激更好的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM