New Splash Screen API from Android
Tags: android, splash, programming, androidstudio
Published: 2022-02-12 11:37:10

---
title: New Splash Screen API from Android
published: true
description: Solve your app's cold start problem with Android's new splash screen library.
tags: android, splash, programming, androidstudio
cover_image: https://ik.imagekit.io/z23yf8euyq/0_q9sk9B7dSsZOl0Pz.png
---

Billions of Android apps are there in play store. Most of the apps have one thing common, Splash Screen. Android 12 brought us the official splash screen support. Previously, we have to add a custom implementation i.e. there was no uniform way to implement it. You can implement this feature in lower versions(minimum SDK 23) also with support library.

## Definition of splash screen
When your app is not in memory or its process is not active, it takes time to open. It takes time to load first frame of your app. Till then even if you implement an activity as splash, you will see a plain white screen for some time. It's better to show some graphical assets i.e. app logo, animation, background color etc. to users instead of showing white screen. This graphic is called **Splash Screen**.

An example of splash screen animation from Android's official document:
![Splash screen demo](https://developer.android.com/about/versions/12/images/splash-screen-gmail-example.gif)

Splash screen will be shown in following scenarios:
1. [**Cold Start**](https://developer.android.com/topic/performance/vitals/launch-time#cold)- A cold start refers to an app’s starting from scratch. Cold starts happen in cases such as your app’s being launched for the first time since the device booted, or since the system killed the app.

2. [**Warm Start**](https://developer.android.com/topic/performance/vitals/launch-time#warm)- Warm start happen when user backs out from the app or when system evicts your app from memory, then user re-launches the app.

## Implementation of Splash Screen API

Let's do some coding together.

### Step 1:
Add following gradle dependency in your app level `build.gradle` file:

```groovy
implementation "androidx.core:core-splashscreen:1.0.0-beta01"
```

Make sure `compileSdkVersion` of your app is `31` or above.

Now sync gradle.

### Step 2:

Create a splash theme in `values/themes.xml`. Also it's night mode counterpart if you are supporting night mode i.e. in `values-night/themes.xml`. Splash theme would look like as follows:

```xml
<style name="Theme.MySplash" parent="Theme.SplashScreen">
        <item name="windowSplashScreenBackground">@color/purple_500</item>
        <item name="windowSplashScreenAnimatedIcon">@drawable/splash_animation</item>
        <item name="postSplashScreenTheme">@style/AppTheme</item>
        <item name="windowSplashScreenAnimationDuration">2000</item>
    </style>
```

where,

- `windowSplashScreenBackground`- is the background color of your splash screen.
- `windowSplashScreenAnimatedIcon`- is the icon resource to display at the centre of splash screen. This could be a normal drawable icon or animated drawable or animated vector drawable.
- `windowSplashScreenAnimationDuration`- Duration(in milliseconds) of centre icon animation if it is animated resource. Keep in mind that, animation here will only work in Android 12 or above.
- `postSplashScreenTheme`- This is the your app theme which will be applied after completion of splash screen.

### Step 3:

Add this theme in `AndroidManifest.xml` file. Your manifest will look like as follows:

```xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.otb.splashdemo">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MySplash">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>
```

see `android:theme="@style/Theme.MySplash"` property.

### Step 4

Inside the launcher activity, call activity's `installSplashScreen()` extension function before `setContentView()`. Below is an example:

```kotlin
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        installSplashScreen()
        setContentView(R.layout.activity_main)
    }
}
```

😃 That's it!!! Really simple steps right?

## Advance Steps

Now what if you want to keep the splash screen till loading some data from local or remote data source? Then you can follow some advance steps:

### Step 5

To keep splash screen even after app came in process, you need to use pre draw listener. Modify your activity as follows:

```kotlin
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        installSplashScreen()
        setContentView(R.layout.activity_main)
        setupPreDrawListener()
    }

    /**
     * Use this method only if you want to keep splash screen for longer than cold start time.
     * Manage `isReady` flag according to your logic.
     */
    private fun setupPreDrawListener() {
        // Set up an OnPreDrawListener to the root view.
        val content: View = findViewById(android.R.id.content)
        content.viewTreeObserver.addOnPreDrawListener(
            object : ViewTreeObserver.OnPreDrawListener {
                override fun onPreDraw(): Boolean {
                    // Check if the initial data is ready.
                    val isReady = true
                    return if (isReady) {
                        // The content is ready; start drawing.
                        content.viewTreeObserver.removeOnPreDrawListener(this)
                        true
                    } else {
                        // The content is not ready; suspend.
                        false
                    }
                }
            }
        )
    }
}
```

where, `isReady` is the flag which should come from your app's logical layer `ViewModel`.

### Step 6
If you want to exit splash screen with some animation, you can do this using extension field `splashScreen`. This will work only for Android 12. Use below method creating custom exit animation:

```kotlin
private fun exitWithSlideUp(){
        splashScreen.setOnExitAnimationListener { splashScreenView ->
            // Create your custom animation.
            val slideUp = ObjectAnimator.ofFloat(
                splashScreenView,
                View.TRANSLATION_Y,
                0f,
                -splashScreenView.height.toFloat()
            )
            slideUp.interpolator = AnticipateInterpolator()
            slideUp.duration = 200L

            // Call SplashScreenView.remove at the end of your custom animation.
            slideUp.doOnEnd { splashScreenView.remove() }

            // Run your animation.
            slideUp.start()
        }
    }
```

For the ease of my readers, I have created [Splash Demo GitHub Repo](https://github.com/mohitrajput987/splash-api-demo) where you can see example implementation of splash screen API.

## Conclusion
First impression is the last impression. If user sees blank screen on launching the app, it will create bad impact. To provide a better user experience, splash screen is a very useful API. To read more about splash screen, you can read [official document](https://developer.android.com/guide/topics/ui/splash-screen).
Blog's banner credit goes to [Wajahat Karim](https://wajahatkarim.com/2019/12/revisited-a-guide-on-splash-screen-in-android-in-2020/).
Thanks for reading my blog. 😇😇😇