How can I use WearableActivity with LiveData and ViewModel

0 votes
asked Sep 12, 2017 by peter

I want to be able to use the Lifecycle components from the new Android Architecture Components in my Wearable app (same as I do in my Android app).

In my main Android app I put 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. So far so good...

The problem I'm facing is that my Wear app is based on the WearableActivity class which extends from android.app.Activity rather than from android.support.v4.app.FragmentActivity. This prevents me from using ViewModelProviders.of in my wearable app.

I've asked around and tried to find alternative solutions, but I don't know the internals of ViewModelProviders so I can't get around this problem right now. If there isn't an answer I hope someone who works on these components can have a look at this. It would be awesome to be able to use ViewModel & LiveData throughout my applications (mobile and wear).

3 Answers

0 votes
answered Sep 12, 2017 by ianhanniballake

This is not yet possible as ViewModel depends on Support Fragments (i.e., FragmentActivity).

Please file a feature request for a WearableFragmentActivity equivalent at issuetracker.google.com

+1 vote
answered Sep 13, 2017 by fp

Update: AmbientMode seems to be the new way to handle this.

As @codingjeremy mentioned in his post, they have now introduced this with Android Support Library 27.0.0.


Original:

I got around this by copying the implementation in WearableActivity verbatim to a new WearableFragmentActivity class defined in my own project and then changing it to extend FragmentActivity. Getting this supported by Google directly would be the ideal solution, but this should work if you're looking for a workaround in the meantime.

0 votes
answered Oct 25, 2017 by codingjeremy

I got it to work using AmbientMode.AmbientCallbackProvider instead of WearableActivity.

It is the new preferred method and it still gives you the onEnterAmbient(), onAmbientUpdate(), and onExitAmbient() but also lets you use Activity (or any sub classes... FragementActivity, etc.)... which allows you to support the Architecture components.

Official docs call out the details and code.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
...