Kotlin:调用一个函数以从BroadcastReceiver onReceive更新UI [英] Kotlin: Call a function to update UI from BroadcastReceiver onReceive

查看:939
本文介绍了Kotlin:调用一个函数以从BroadcastReceiver onReceive更新UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Kotlin的新手,它真棒!尽管今天,我一直在尝试做一些Java超级简单的事情,但是我完全陷入了困境.

I am new to Kotlin, and it seems awesome! Though today, I've been trying to do something that in Java was super simple, but I've got totally stuck.

我正在使用广播接收器来确定设备何时与电源连接/断开.我需要做的就是相应地更新我的UI.

I am using a broadcast receiver to determine when the device is connected/ disconnected from a power source. And all I need to do it update my UI accordingly.

这是我的BroadcastReceiver类,它似乎工作正常.

Here's my BroadcastReceiver classs, and it seems to work fine.

class PlugInReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val action = intent.action

        if (action == Intent.ACTION_POWER_CONNECTED) {
            // Do stuff when power connected
        } 
        else if (action == Intent.ACTION_POWER_DISCONNECTED) {
            // Do more stuff when power disconnected
        }
    }
}

现在在我的MainActivity中(但稍后在其他地方),我想在触发意图时更新UI,例如,在下面的函数中,背景颜色会更改.

Now in my MainActivity (but somewhere else, later on), I want to update my UI when the intent is fired, for example in the function below, the background color changes.

private fun updateBackgroundColor( newBgColorId: Int = R.color.colorAccent){
    val mainLayout = findViewById<View>(R.id.mainLayout)
    val colorFade = ObjectAnimator.ofObject(
            mainLayout, "backgroundColor", ArgbEvaluator(), oldBgColor, newBgColor)
    colorFade.start()
}


问题

BroadcastReceiver触发事件时,如何在MainActivity上调用函数或更新UI?

How can I call a function on the MainActivity, or update my UI when the BroadcastReceiver fires an event?


到目前为止我尝试过的一切

  • 我研究了在某个地方有一个静态变量,存储了BroadcastReciever的结果,然后在我的UI类中添加了一个可观察的结果,并相应地观察和调用了适当的函数的情况.尽管在谷歌搜索后如何执行此操作,看来在Kotlin中这并不是一个好方法.


    What I've tried so far

    • I looked into having a static variable somewhere, storing the result of the BroadcastReciever, then an observable in my UI class, watching and calling appropriate function accordingly. Though after Googling how to do this, looks like that's not really a good approach in Kotlin.

      考虑尝试在UI线程上运行BroadcastReciever,但这听起来像是一个糟糕的主意.

      Considered trying to run the BroadcastReciever on the UI thread, but that sounds like a terrible idea.

      试图将Java实现与我的Kotlin类混合使用,但无法使其正常工作.

      Tried mixing a Java implementation with my Kotlin class, but couldn't get it to work.

      令人沮丧的是,我在SO上发现了几个非常相似的问题.但是,它们的实现似乎都使用特定于Java的功能:

      Frustratingly I found several very similar questions on SO. However their implementations seem to all use Java-specific features:

      • Android BroadcastReceiver onReceive Update TextView in MainActivity
      • How to update UI in a BroadcastReceiver
      • Calling a Activity method from BroadcastReceiver in Android
      • How to update UI from BroadcastReceiver after screenshot

      对于大多数Android开发人员,我确定这是一个琐碎的问题,但是我迷路了!让我知道是否需要更多详细信息.提前非常感谢!

      I'm sure this is a trivial question for most Android developers, but I am lost! Let me know if you need any more details. Thanks very much in advance!

      推荐答案

      共享信息以在Kotlin中注册BroadcastReceiver

      Sharing the info to register BroadcastReceiver in Kotlin

      步骤1.在MainActivity.kt中创建BroadcastReceiver

      Step 1. Create BroadcastReceiver in MainActivity.kt

      private val mPlugInReceiver = object : BroadcastReceiver() {
          override fun onReceive(context: Context?, intent: Intent?) {
              when (intent?.action) {
                  Intent.ACTION_POWER_CONNECTED -> {
                      //update your main background color
                      updateBackgroundColor()
                  }
                  Intent.ACTION_POWER_DISCONNECTED -> {
                      //update your main background color
                      updateBackgroundColor()
                  }
              }
          }
      }
      

      第2步.创建IntentFilter

      Step 2. Create IntentFilter

      private fun getIntentFilter(): IntentFilter {
          val iFilter = IntentFilter()
          iFilter.addAction(Intent.ACTION_POWER_CONNECTED)
          iFilter.addAction(Intent.ACTION_POWER_DISCONNECTED)
          return iFilter
      }
      

      第3步.在onStart()注册接收者

      Step 3. Register receiver at onStart()

      override fun onStart() {
          super.onStart()
          registerReceiver(mPlugInReceiver, getIntentFilter())
      }
      

      第4步.在onStop()上注销接收器

      Step 4. Unregister receiver at onStop()

      override fun onStop() {
          super.onStop()
          unregisterReceiver(mPlugInReceiver)
      }
      

      如果您具有自定义的BroadcastReceiver,则可以使用LocalBroadcastManager注册并创建本地IntentFilter

      If you have custom BroadcastReceiver, you can register using LocalBroadcastManager and create your local IntentFilter

      private val mLocalBroadcastReceiver = object : BroadcastReceiver() {
          override fun onReceive(context: Context?, intent: Intent?) {
              when (intent?.action) {
                  AnyService.UPDATE_ANY -> {
      
                  }
              }
          }
      }
      
      private fun getLocalIntentFilter(): IntentFilter {
          val iFilter = IntentFilter()
          iFilter.addAction(AnyService.UPDATE_ANY)
          return iFilter
      }
      

      注册本地接收者 LocalBroadcastManager.getInstance(applicationContext).registerReceiver(mLocalBroadcastReceiver, getLocalIntentFilter())

      取消注册本地接收者LocalBroadcastManager.getInstance(applicationContext).unregisterReceiver(mLocalBroadcastReceiver)

      这篇关于Kotlin:调用一个函数以从BroadcastReceiver onReceive更新UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆