I could find two methods to implement splash screen:
public class MainSplashScreen extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_splash_screen);
// METHOD 1
/****** Create Thread that will sleep for 5 seconds *************/
Thread background = new Thread() {
public void run() {
try {
// Thread will sleep for 5 seconds
sleep(5*1000);
// After 5 seconds redirect to another intent
Intent i=new Intent(getBaseContext(),MainActivity.class);
startActivity(i);
//Remove activity
finish();
} catch (Exception e) {
}
}
};
// start thread
background.start();
//METHOD 2
/*
new Handler().postDelayed(new Runnable() {
// Using handler with postDelayed called runnable run method
@Override
public void run() {
Intent i = new Intent(MainSplashScreen.this, MainActivity.class);
startActivity(i);
// close this activity
finish();
}
}, 5*1000); // wait for 5 seconds
*/
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
As expected,both methods first show the splash screen for 5 seconds and then start the MainActivity.
In my App, MainActivity is relatively time consuming to initiate. Therefore, what I see in both methods is the splash screen for 5 seconds and then a black display for a few seconds (like when I do not use splash screen) and then the MainActivity.
The question is how can I initiate the MainActivity during presentation of the splash screen.
I tried to define two threads and run simultanously but the result is exactly like when I do not use splash screen.
Thread background = new Thread() {
public void run() {
try {
sleep(5*1000);
finish();
} catch (Exception e) {}
}
};
Thread mainTh = new Thread() {
public void run() {
try {
Intent i=new Intent(getBaseContext(),MainActivity.class);
startActivity(i);
} catch (Exception e) {}
}
};
mainTh.start();
background.start();
try this,
public class Splash extends Activity {
private static final int SPLASH_SHOW_TIME = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Fabric.with(this, new Crashlytics());
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splash);
new BackgroundSplashTask().execute();
}
private class BackgroundSplashTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0) {
try {
Thread.sleep(SPLASH_SHOW_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Intent i = new Intent(Splash.this, MainActivity.class);
startActivity(i);
finish();
}
}
}