2
votes

I have an splash activity which should appear for a brief period of time before the home activity launches. This is my code:

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class SplashActivity extends Activity {

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



     /****** Create Thread that will sleep for 5 seconds *************/        
    Thread background = new Thread() {
        public void run() {

            try {
                // Thread will sleep for 2.5 seconds
                sleep(2500);



                //Remove activity
                finish();

                // After 2.5 seconds redirect to another intent
                Intent i=new Intent(getBaseContext(),HomeActivity.class);
                startActivity(i);

            } catch (Exception e) {

            }
        }
    };

    // start thread
    background.start();


}

@Override
protected void onDestroy() {

    super.onDestroy();

  }

}

Currently this works perfectly except for the fact that when I go back to home screen (without explicitly killing the app), and resume it, it shows the splash screen again. How do I ensure the splash screen appears only when I launch the app afresh?

2
This is a bit unclear. The app is launched "fresh" from the homeacreen if the Activity has been destroyed (user press back or OS explicitly destroys the app). Or, the app is resumed if the user press the home button or e.g. gets a call. Please specify what you mean with "launch the app fresh". If you mean each time a new instance is created, my answer is working as you intend it to. - Marcus
what i mean is, if currently no app instance is running, I want splash screen to display. Upon going into the app, if I press home button, and then click on the app icon, I do not want the splash screen to display, because an existing app instance would already be running. - SoulRayder

2 Answers

1
votes

Use noHistory and excludeFromRecent attribute in your manifest. In addition add the flags Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP to the intent used to start your real activity.

Edit: put android:launchMode="singleTop" in your real main activity and use the intent flag (in combination of the others) FLAG_ACTIVITY_NEW_TASK.

-2
votes

I suggest you to save a preference containing the current timestamp in your SplashActivity's onCreate() method. The next time you open the app, check if the difference between the saved timestamp and the current timestamp is greater than an arbitrary value (a sort of grace period) and decide to show/avoid the splash screen.