July 28, 2022
In order to add a splash screen we'll use the react-native-splash-screen package. While most of the job is done by following the installation steps, there are some additional steps we need to follow for android.
There's a concept known as the "preview window" in android which serves a basic purpose of faking a fast launch of app when the app icon is clicked. While preview window fakes fast launching, it shows an empty white screen until the app has loaded. More info available in this article.
The preview window can itself be disabled by adding the following line in the
android/app/src/main/res/values/styles.xml
file.
<item name="android:windowDisablePreview">true</item>
However disabling the preview window introduces an undesirable delay between clicking on the app icon and the actual launching of the app.
We can get rid of the delay and the empty white screen by adding an additional splash activity.
Create a background_splash.xml file with the same design you used in
launch_screen.xml
during the installation above.
Place this new xml file inside the android/app/src/main/res/drawable
directory.
Create a new splash theme in the android/app/src/main/res/values/styles.xml
file by adding the following snippet.
<style name="SplashTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowBackground">@drawable/background_splash</item>
</style>
Create a new splash activity to call the main activity, and add the following code in it.
package com.example;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
public class SplashActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
Finally we will call this activity first on launch with the splash theme we created above.
Add the new activity in AndroidManifest.xml.
<activity android:name=".SplashActivity" android:label="@string/app_name" android:launchMode="singleTask" android:theme="@style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
The intent-filter tag, with its "MAIN" action and "LAUNCHER" category
children, allows us to call this new activity first on launch. It's usually
found in the main activity by default, so we have to remove them entirely from
there, leaving them exclusively in SplashActivity
.
Once we've done all this, we can rebuild the app and run it with
npx react-native run-android
to see the splashscreen we created.
The app should now launch quickly with no empty white screen on startup.
If this blog was helpful, check out our full blog archive.