Android Activity Life Cycle: Problems with Onstop()

Rehan :

So Basically what I want to do is simply change some values in the database when an App is minimized or Stopped!

This is how my code looks like:

  @Override
    protected void onStop() {
        super.onStop();

        FirebaseUser currentUser = mAuth.getCurrentUser();

        if(currentUser != null) {

            mUserRef.child("online").setValue(ServerValue.TIMESTAMP);

        }

    }

But the problem is when I call startActivity(startInten) i.e move to second intent this method is called at that time as well. I have researched a lot on the internet. Can anyone tell me which activity lifecycle method is the one which is only called when the app is minimized and killed and not when we intent to other activity within the same app?

Thanks.

user3783123 :

You should use ProcessLifecycleOwner from android lifecycle library and observe it from application class onCreate method.

Sample code (in kotlin):

ProcessLifecycleOwner.get().lifecycle.addObserver(object : LifecycleObserver{
        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun onStop(){
            val currentUser = mAuth.getCurrentUser()
            if (currentUser != null) {
                mUserRef.child("online").setValue(ServerValue.TIMESTAMP)
            }
        }
    })

Sample code (in Java):

ProcessLifecycleOwner.get().getLifecycle().addObserver(new LifecycleObserver() {
        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        public void onStop(){
            FirebaseUser currentUser = mAuth.getCurrentUser();
            if(currentUser != null) {
                mUserRef.child("online").setValue(ServerValue.TIMESTAMP);
            }
        }
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        public void onStart(){
            //onstart action here
        }
}

This is going to get called when the last activity has called onStop and app has moved to background or killed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=309832&siteId=1