【问题标题】:How to pass data from BroadcastReceiver to one other class?如何将数据从 BroadcastReceiver 传递到另一个类?
【发布时间】:2021-10-29 21:28:21
【问题描述】:

我正在开发一个应用程序,用于使用蓝牙扫描设备。 从 Android Studio 的文档中,我发现了如何扫描设备并在发现设备时执行操作:

override fun onCreate(savedInstanceState: Bundle?) {
   ...

   // Register for broadcasts when a device is discovered.
   val filter = IntentFilter(BluetoothDevice.ACTION_FOUND)
   registerReceiver(receiver, filter)
}

// Create a BroadcastReceiver for ACTION_FOUND.
private val receiver = object : BroadcastReceiver() {

   override fun onReceive(context: Context, intent: Intent) {
       val action: String = intent.action
       when(action) {
           BluetoothDevice.ACTION_FOUND -> {
               // Discovery has found a device. Get the BluetoothDevice
               // object and its info from the Intent.
               val device: BluetoothDevice =
                       intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
               val deviceName = device.name
               val deviceHardwareAddress = device.address // MAC address
           }
       }
   }
}

问题是:如果我要创建一个用于扫描设备的类,我如何才能为发现的每个设备将其传递给我的主类 (MainActivity)?。

我想在扫描类中使用观察者和观察一个特定的变量,但我不知道这是否是一个好习惯。

【问题讨论】:

    标签: android android-studio kotlin mvvm bluetooth


    【解决方案1】:

    您可以使用 ViewModel 类并在此处保存所有数据。您可以在任何课程中获取您的 ViewModel。 https://developer.android.com/topic/libraries/architecture/viewmodel

    【讨论】:

    • ViewModel 类不应该与视图(UI)相关联吗?事实是我没有用这个类更新视图..
    猜你喜欢
    • 1970-01-01
    • 2019-10-15
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多