Michał Powłoka
Michał Powłoka

Reputation: 1511

How to get LifecycleOwner in WearableActivity?

I am facing a problem when I try to use LiveData from WearableActivity:

val livedata = ...
val observer = ...
livedata.observe(this, observer)

It worked when I was working with activity extending AppCompatActivity but it looks like WearableActivity does not implement LifecycleOwner interface, altough it does own a lifecycle, right? (observe method requires LifecycleOwner as the first argument). How can I make it work?

Upvotes: 4

Views: 2199

Answers (1)

Doplgangr
Doplgangr

Reputation: 76

The latest approach as shown on the official Android sample projects is to extend androidx.fragment.app.FragmentActivity and implement AmbientModeSupport.AmbientCallbackProvider.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // setContentView will be the same as before
    setContentView(R.layout.activity_main)

    // Initialize yourCustomObserver here or have it injected

    // FragmentActivity has getLifeCycle() so you get it for free
    getLifeCycle().addObserver(yourCustomObserver);
}

That's it, and you won't need to manually update your LifecycleOwner (aka Activity) lifecycle state.

Previous Answer

Further to the previous comment by Karan Modi, you may implement your own getLifeCycle() according to the guide in the lifecycle documentation.

https://developer.android.com/topic/libraries/architecture/lifecycle.html#implementing-lco

Specifically, you may implement your own LifeCycleOwner as shown:

public class MyActivity extends WearableActivity implements LifecycleOwner {
    private LifecycleRegistry mLifecycleRegistry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mLifecycleRegistry = new LifecycleRegistry(this);
        mLifecycleRegistry.markState(Lifecycle.State.CREATED);
    }

    @Override
    public void onStart() {
        super.onStart();
        mLifecycleRegistry.markState(Lifecycle.State.STARTED);
    }

    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
}

Hope this helps.

Upvotes: 6

Related Questions