Search code examples
androidsplash-screen

Start Splash screen every time if user press home button or back button from main activity


I have two activity. 1] splash screen 2]MainActivity

Once splash screen task over it moves to next MainActivity.. But my requirement is ..If user press home button or backPress . and when user resume application again,it should start with splash screen,not from MainActivity.

thankx in advance


Solution

  • I am seeing every answer here says to override the onResume() method. This is a bad idea. Why? Well, when you are in the MainActivity and you get a call, you can still see the activity in the background, as it is in the onPause() state. When you dismiss the call, onResume() will be called and then SplashActivity will be called. This is not a good user experience and not what you might be looking for.

    Also, onResume() gets called during the creation of MainActivity. So if you put the startActivity() code in onResume() without any conditional check, you will never see MainActivity itself. SplashActivity will start immediately when MainActivity is created.


    So, how to accomplish what you want?

    1. Once you start MainActivity from SplashActivity, don't finish() the SplashActivity. Let it remain in the back stack, so when you press back button, you will go to SplashActivity.

    2. In the onStop() method of your MainActivity set a flag to note that MainActivity is minimized. Then in onStart() check for this flag and start SplashActivity only if this flag is set. This is to make sure that the app is minimized and is resuming.

    MainActivity:

     private boolean isMinimized = false;
    
     @Override
     protected void onStop() {
          super.onStop();
          isMinimized = true;
     }
    
     @Override
     protected void onStart() {
          super.onStart();
    
          if(isMinimized){
              startActivity(new Intent(this , SplashActivity.class));
              isMinimized = false;
              finish();
          }
     }