Search code examples
androidandroid-activity

Avoiding double instance of activity in android


I've done a simple content based application. App always launch with splash screen. After 3 sec it goes to MainActivity from SpalshActivity. But am facing a problem. If i press back button when app showing splash screen and again launch the app from device app list then app start normally but then I have to press back icon twice to quit the app. Because app has another instance of MainActivity from previous launch.

How can I avoid this double instance ?

public class SplashActivity extends Activity {

private static int SPLASH_TIME_OUT = 2000;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash_screen);

    new Handler().postDelayed(new Runnable() {


        @Override
        public void run() {

            Intent i = new Intent(SplashActivity.this,
                    MainActivity.class);
            startActivity(i);

            finish();
        }
    }, SPLASH_TIME_OUT);
}

 }

Solution

  • Let me summarise the symptoms first

    • You launch the app.
    • Press back while the splash screen is displayed
    • Re-Launch the app which shows the splash screen followed by MainActivity
    • Press back which shows another MainActivity
    • Press back again which exits the app

    The reason is that your postDelayed hander still runs even though you press back. Your phone is correctly starting SplashActivity but another MainActivity is being launched from the old SplashActivity.

    You need to remove your postDelayed callback when you go into the background. Keep a reference to that Handler and call removeCallbacksAndMessages. I would normally start postDelayed in onResume and remove it in onPause

    Alternatively you can launch MainActivity with the FLAG_ACTIVITY_CLEAR_TOP flag. That flag indicates that if MainActivity already exists in the back stack it should be brought to the front and activities above it should be closed. You can also add FLAG_ACTIVITY_SINGLE_TOP if you want it to re-use the same activity instance instead of creating a new one.