我需要在LifecycleObserver中获取LifecycleOwner,以便将其传递给ViewModel观察者。
这是我的MainActivity,我在其中添加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;
}
}
这是我的观察者,我需要LifecycleOwner。
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);
});
}
}
@OnLifecycleEvent
已被弃用。请参考https://developer.android.com/jetpack/androidx/releases/lifecycle#2.4.0-beta01。 - Akito