如何将 WearableActivity 与 LiveData 和 ViewModel 一起使用

How can I use WearableActivity with LiveData and ViewModel

我希望能够在我的可穿戴应用程序中使用来自新 Android 架构组件的生命周期组件(与我在 Android 应用程序中所做的一样)。

在我的主要 Android 应用程序中,我放置了 LiveData fields in a ViewModel. This ViewModel can then be accessed/bound from both my Activity and my Fragments. To do this I use the method ViewModelProviders.of which expects either android.support.v4.app.Fragment or android.support.v4.app.FragmentActivity。到目前为止一切顺利...

我面临的问题是我的 Wear 应用程序基于我的可穿戴应用程序中的 WearableActivity class which extends from android.app.Activity rather than from android.support.v4.app.FragmentActivity. This prevents me from using ViewModelProviders.of

我四处打听并试图找到替代解决方案,但我不了解 ViewModelProviders 的内部结构,所以我现在无法解决这个问题。如果没有答案,我希望从事这些组件工作的人可以看看这个。如果能够在我的应用程序(移动和可穿戴设备)中使用 ViewModel 和 LiveData 会很棒。

这还不可能,因为 ViewModel 取决于支持片段(即 FragmentActivity)。

请在 issuetracker.google.com

提交 WearableFragmentActivity 等效项的功能请求

更新: AmbientMode 似乎是处理此问题的新方法。

正如@codingjeremy 在他的 post 中提到的,他们现在已经通过 Android 支持库 27.0.0 引入了这个。


原文:

我通过将 WearableActivity 中的实现逐字复制到我自己的项目中定义的新 WearableFragmentActivity class 然后更改它以扩展 FragmentActivity 来解决这个问题。直接获得 Google 的支持将是理想的解决方案,但如果您同时正在寻找解决方法,这应该可行。

我使用 AmbientMode.AmbientCallbackProvider 而不是 WearableActivity 让它工作。

这是新的首选方法,它仍然为您提供 onEnterAmbient()onAmbientUpdate()onExitAmbient(),但也允许您使用 Activity(或任何子 类...FragementActivity 等)...它允许您支持架构组件。

Official docs call out the details and code.

您可以使用此架构组件移植:LifeCycleData