Reputation: 1040
I have a SplashScreenActivity which will run every 2 minutes if there is no touch detected on the MainActivity. If the 'Start' button is pressed on the SplashScreenActivity, it starts MainActivity.
My problem is when the 'Start' button is pressed on the SplashScreenActivity, a new instance of MainActivity is created each time, thus loading up my libraries and initialization each time (in OnCreate()). This significantly slows down my application and lags when the button is pressed. I only want this to run once when the application is first started.
I have tried using
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
@Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(SplashScreen.this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
...when the Intent has started, but my libraries and initialization in OnCreate() in MainActivity are still being run again.
When 'Start' button pressed in SplashScreenActivity, runs the following method:
public void startIntent(View v){
Intent i = new Intent(SplashScreen.this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
Any help?
Currently have the lines (taken out setFlags):
Intent intent = new Intent(Email.this, MainActivity.class);
startActivity(intent);
And still MainActivity's OnCreate() is being called each time the activity has started.
So I've found out that if I set the following:
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
I can successfully return to my MainActivity without it creating a new instance.
Click here for more info.
Upvotes: 2
Views: 1783
Reputation: 874
If you just want to show a SplashScreen (meaning a picture), then you should consider to make an ImageView within any layout on the same level as the main layout.
Then you can make the ImageView/SplashScreen visible or invisble in your code.
This way you may save a lot of work.
Upvotes: 1
Reputation: 22342
Intent.FLAG_ACTIVITY_CLEAR_TOP
clears everything on top of the target activity in the stack. In your case, when you call the SplashScreen, you're telling the MainActivity to close itself.
Upvotes: 1