当我尝试使用 Wea​​rableActivity 中的 LiveData 时遇到问题:

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

当我使用扩展 AppCompatActivity 的 Activity 时它工作,但看起来 WearableActivity 没有实现 LifecycleOwner 接口(interface),尽管它确实拥有生命周期,对吧? (observe 方法需要 LifecycleOwner 作为第一个参数)。我怎样才能让它工作?

最佳答案

官方 Android sample projects 上显示的最新方法是扩展 androidx.fragment.app.FragmentActivity 并实现 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);
}
就是这样,您不需要手动更新 LifecycleOwner(又名 Activity)生命周期状态。
上一个答案
继 Karan Modi 之前的评论之后,您可以根据生命周期文档中的指南实现自己的 getLifeCycle()
https://developer.android.com/topic/libraries/architecture/lifecycle.html#implementing-lco
具体来说,您可以实现自己的 LifeCycleOwner,如下所示:
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;
    }
}
希望这可以帮助。

关于android - 如何在 WearableActivity 中获取 LifecycleOwner?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48260060/

10-12 03:50