21

I have an Android App, which shows a "Splash Screen" for 3 seconds. After that, the MainActivity gets loaded.

Unfortunately the MainActivity takes additional ~4 seconds to load. On first startup even longer. However when the App is loaded, everything runs smooth.

Now how can I achieve it, that the MainActivity gets loaded, during the display of the Splash Screen? It just should display an image until the whole thing loaded completely. I have read about Async-Task, but I'm not sure where to put it and how to use it properly. Can someone help me please?

SplashScreen.java

public class SplashScreen extends Activity {
    private static int SPLASH_TIME_OUT = 3000;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_startup);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent i = new Intent(SplashScreen.this, MainActivity.class);
                startActivity(i);
                finish();
            }
        }, SPLASH_TIME_OUT);
    }
}

MainActivity.java

public class MainActivity extends Activity implements OnClickListener, MediaController.MediaPlayerControl {

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

        //Some heavy processing
        //starting services
        //starting Google Text to Speech
        //and so on...

    }

}
HorstB
  • 243
  • 1
  • 2
  • 5
  • 2
    One workaround may be to use only `MainActivity`, initially displaying splash screen layout, later hiding/removing it (via the `Handler.postDelayed()`, for example) to show the actual Activity layout. – Mikhail Jul 17 '15 at 10:22
  • This new tip from the Android Developers might be helpful: https://plus.google.com/+AndroidDevelopers/posts/Z1Wwainpjhd – Gerald Schneider Jul 17 '15 at 10:23
  • Have you googled yet?There are tons of example for you.Check this http://www.androidhive.info/2013/07/how-to-implement-android-splash-screen-2/ – Soham Jul 17 '15 at 10:36
  • 1
    Thanks for the comments! @Soham: My sample code is from exactly the same source like your link... So YES I have googled it. My problem however was solved **here** by TmKVU – HorstB Jul 17 '15 at 13:08

6 Answers6

49

You should not be creating a new thread on startup, instead you should create a view that does not have to wait for your resources to load, as detailed in this article: Splash Screens the Right Way.

As stated in the article, you should create a layer-list drawable instead of a layout XML file:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Fill the background with a solid color -->
    <item android:drawable="@color/gray"/>

    <!-- Place your bitmap in the center -->
    <item>
        <bitmap
            android:gravity="center"
            android:src="@mipmap/ic_launcher"/>
    </item>

</layer-list>

Then create a theme using the drawable file as a background. I use the background attribute instead of the windowBackground attribute as suggested in the article, because background takes the status and navigation bars into account, centering the drawable better. I also set windowAnimationStyle to null so that the splash screen does not animate the transition to the MainActivity:

<resources>

    <!-- Base application theme -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

    <!-- Splash Screen theme -->
    <style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
        <item name="android:background">@drawable/background_splash</item>
        <item name="android:windowAnimationStyle">@null</item>
    </style>

</resources>

Then declare your theme in the manifest for your SplashActivity:

<activity android:name=".SplashActivity"
    android:theme="@style/SplashTheme">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

And finally all you have to do in your SplashActivity is start your MainActivity, and the splash screen will only show for as long as it takes for your app to configure:

public class SplashActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }
}
Bryan
  • 14,756
  • 10
  • 70
  • 125
  • 4
    This should be the accepted answer. It actually answers OP's question. – wsgeorge Dec 10 '16 at 08:09
  • 1
    Good approach, but can we display a progress bar in the splash screen created this way? – Niraj Niroula Feb 17 '17 at 09:38
  • 1
    @Journey No, the point is to show this screen before the resources are loaded. In order to show a progress bar, the resources would have to be loaded. An application shouldn't take that long to load its resources anyway, a matter of seconds. If your application handles a some other processes on startup, a good method to handle this would be to have a `SplashActivity` that starts a `LoadingActivity` which will handle those processes. If you use the same `windowBackground`, there will be no visual difference between the two, except now you can display a progress bar. – Bryan Feb 17 '17 at 14:03
  • 1
    thanks a lot but dont forget to add parent="Theme.AppCompat.NoActionBar" to the SplashTheme style, it will not work without it – Hoby Sep 26 '17 at 12:40
  • Thanks @Bryan, everthing works fine except android stretches the bitmap and the image overflow its boundaries. Do you have any idea (my minimum api level is 19) – Huseyin Sahin Mar 18 '19 at 08:12
  • 1
    @HuseyinSahin The drawable used to create the bitmap should adhere to the intrinsic `dp` size of the drawable; so just use a smaller drawable, no? Layer drawables do have [`width`](https://developer.android.com/reference/android/graphics/drawable/LayerDrawable.html#attr_android:width) and [`height`](https://developer.android.com/reference/android/graphics/drawable/LayerDrawable.html#attr_android:height) attributes to override the intrinsic size, but according to Android Studio they are not supported until API level 23 (I'm not sure why this isn't reflected in the documentation). – Bryan Mar 18 '19 at 12:56
  • Exactly what I needed! Thanks so much! – ConcernedHobbit Apr 04 '20 at 00:36
  • 2
    If you get the "Resources $ NotFoundException" error, try this for the second item in the layer-list: (without bitmap tag) `` – Mahmut K. May 09 '20 at 01:13
17

If there are no specific constraints about the time the splash screen should be shown, you could use the AsyncTask in the following way:

public class SplashScreen extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_startup);
        startHeavyProcessing();

    }

    private void startHeavyProcessing(){
       new LongOperation().execute("");
    }

    private class LongOperation extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            //some heavy processing resulting in a Data String
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.interrupted();
                }
            }
            return "whatever result you have";
        }

        @Override
        protected void onPostExecute(String result) {
            Intent i = new Intent(SplashScreen.this, MainActivity.class);
            i.putExtra("data", result);
            startActivity(i);
            finish();
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }
}

If the resulting data if of another nature than a String you could put a Parcelable Object as an extra to your activity. In onCreate you can retrieve the data with:

getIntent().getExtras.getString('data');

TmKVU
  • 2,910
  • 2
  • 16
  • 30
1

How about, in the interest of simplicity, you combine your splash activity with your main activity? That way you get the best of both worlds, namely a splash screen while your data is preparing the first time, and a quick startup when it's been prepared previously. Making the user wait for nothing is not really good form...

Something like:

public class MainActivity extends Activity implements OnClickListener, MediaController.MediaPlayerControl {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Initially shows splash screen, the main UI is not visible
        setContentView(R.layout.activity_main);  

        // Start an async task to prepare the data. When it finishes, in
        // onPostExecute() get it to call back dataReady()
        new PrepareDataAsyncTask(this).execute();

    }

    public void dataReady() {
        // Hide splash screen
        // Show real UI
    }

}
Theo Lassonder
  • 1,019
  • 9
  • 16
0

your splash screen code works fine but when you call next activity then in onCreate() use Asynctask for your heavy tasks...

Puneet Kumar
  • 306
  • 1
  • 3
0

I have had similar problem. There was a blank loading screen (not even toolbar). Mu culprit was in the manifest in the MainActivity:

 android:launchMode="singleInstance"
Mateusz Kaflowski
  • 2,221
  • 1
  • 29
  • 35
0

Just do like in this article:

1 - create a XML layout like this for the splash screen. I called it "background_splash.xml"

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:drawable="@color/cardview_light_background"/>

    <item>
        <bitmap
            android:gravity="center"
            android:src="@drawable/kiss_com_sub_logo"/>
    </item>

</layer-list>

2 - Then, go to the styles.xml and write a style like this:

<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
        <item name="android:windowBackground">@drawable/background_splash</item>
</style>

3 - Write an activity to your splash. I called it SplashActivity.kt

class SplashActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
        finish()
    }
}

4 - Finally, go to you AndroidManifest.xml and add your activity splash: (Note: don't remove anything in the AndroidManifest, just add this before the Main activity).

<activity
       android:name=".SplashActivity"
       android:label="Kiss"
       android:theme="@style/SplashTheme">
       <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER"/>
       </intent-filter>
</activity>

This is done. You don't need to worry about the time that your application will demand to start, the splash will be there just for enough time. When your MainActivity is ready, it will be showed.

Zain
  • 37,492
  • 7
  • 60
  • 84
Michel Fernandes
  • 1,187
  • 9
  • 8