Search code examples
androidandroid-lifecycleandroid-tabactivityandroid-wake-lock

How to detect whether onResume() is called from onCreate(), from application wake up or from switch activities?


I am a little bit confused about how android's lifecycle works and how to detect the source of function call such like onResume.

Let me state this problem this way. I have an app which contains 5 activities, they will be navigated using a tab activities.

So after switch each tab, I know the onPause() for the current activity and onResume() of the new activity will be called.

Say at activity B, I press the back button, and then I go back to the android's main screen. After I re-open the application, the activity B will be onResume().

What I hope to achieve is that, when the an activities is resumed from main screen, the contents and data will be refreshed. But they should remain unchanged during the tab switch.

Is there any way I could achieve this? How could I know whether an activity is resumed from android main screen or from tab switch?

Thank you!


Solution

  • I don't know how your app logic is set up but you can always have a public static variable somewhere that you can change to hold a tag for the lastScreen.

    e.g:

    Put this in your main activity for example :

    public enum LastScreen {
            NONE, TAB1, TAB2 , TAB3 , MAIN_SCREEN
        }
    
    public static LastScreen lastScreen = LastScreen.NONE;
    

    and in every tab do the following before you switch :

    MainActivity.lastScreen = LastScreen.TAB1;
    

    and in onResume() you can check for it :

    if(MainActivity.lastScreen == LastScreen.TAB1)
       //do something!
    else if (MainActivity.lastScreen == LastScreen.MAIN_ACTIVITY)
       //do something else!