Lifecycle State always INITIALIZED
Im trying to call a custom dialog only if the app has started.
if (mGameActivity.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED)) {
mDialogWinByLeft.show(mGameActivity.getSupportFragmentManager(), "");
}
But the current state is always INITIALIZED.
Im implementing the interface LifecycleRegistryOwner
over GameActivity
.
Sorry if I didnt understand well this new api. Thanks
Solution 1:
Based on your description I would hazard a guess that you are checking the state in onCreate
. During the onCreate
the lifecycle state is only INITIALIZED
.
See this diagram from Google.
Google Lifecycle State Diagram (link broken but can be accessed on wayback machine)
That said you can use the annotation library to observe when you have entered the STARTED
state.
@OnLifecycleEvent(Lifecycle.EVENT.ON_START)
void doSomething(){
//do the thing that needs the lifecycle to be at least started
}
That said this is called after every onStart is finished. So it may be prudent to bake in some logic to determine if this is the appropriate time to do the things that need doing.
Also to make this code work, the class that is to observe the Lifecycle event must implement LifecycleObserver
. This could be any class or even the Activity or Fragment itself. The below code is for a general class/module that will act as a Lifecycle observer.
public class LifeCycleObserverModule implements LifecycleObserver {
LifeCycleObserverModule(Lifecycle lifecycle) {
//register the life cycle to observe
this.lifecycle = lifecycle;
this.lifecycle.addObserver(this);
}
}
If you were to make an Activity observe it's own Lifecycle it would be something like:
public class MainActivity extends AppCompatActivity implements LifecycleObserver {
@Override
protected void onCreate(Bundle savedInstanceState) {
getLifecycle().addObserver(this)
}
}
For a fragment it works the same, but it could observer it's own Lifecycle or that of the activity. If you wanted it to observe the Activity's Lifecycle you could do this. Otherwise it would be the same way as you would do it for the Activity example above.
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
getActivity().getLifecycle().addObserver(this);
}
One final note, I am not entirely clear on if an Activity or Fragment observing it's own Lifecycle is best practice. But it does work, and there seems to be no ill effects from doing so. I am currently using the above method in a couple of Apps I am working on.
EDIT: Corrected the example code. It used to say @OnLifecycleEvent(Lifecycle.EVENT.STARTED)
as was pointed out in a comment STARTED
does not exist, the proper value was ON_START
. Sorry for the mixup.