我需要让lifecycleobserver中的lifecycleowner将其传递给viewmodel观察者。
这是我的主要活动,如果我添加了lifecycleobserver。

public class MainActivity extends AppCompatActivity implements LifecycleOwner{

    private LifecycleRegistry mLifecycleRegistry;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.container, MainFragment.newInstance())
                    .commitNow();
        }

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


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

}

这是我的观察者,我需要生命周期拥有者。
public class MyLifecycleObserver implements LifecycleObserver {


    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onStartListener(){

        FirebaseMassage.startFirebase();

        MainFragment.massageViewModel.getMassage().observe(/*here I need the LifecycleOwner*/, textMassage -> {
            FirebaseMassage.updateFirebaseMassage(textMassage);
        });

    }
}

最佳答案

您可以使用另一个签名来获得如下LifecycleOwner

public class MyLifecycleObserver implements LifecycleObserver {


    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onStartListener(LifecycleOwner owner){
        ...
    }
}

10-08 19:01