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.
1<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.
Additional steps for android
-
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.
1<style name="SplashTheme" parent="Theme.AppCompat.Light.NoActionBar"> 2 <item name="android:windowBackground">@drawable/background_splash</item> 3</style>
-
Create a new splash activity to call the main activity, and add the following code in it.
1package com.example; 2 3import android.content.Intent; 4import android.os.Bundle; 5import androidx.appcompat.app.AppCompatActivity; 6 7public class SplashActivity extends AppCompatActivity { 8 @Override 9 protected void onCreate(Bundle savedInstanceState){ 10 super.onCreate(savedInstanceState); 11 12 Intent intent = new Intent(this, MainActivity.class); 13 startActivity(intent); 14 finish(); 15 } 16}
-
Finally we will call this activity first on launch with the splash theme we created above.
-
Add the new activity in AndroidManifest.xml.
1<activity android:name=".SplashActivity" android:label="@string/app_name" android:launchMode="singleTask" android:theme="@style/SplashTheme"> 2 <intent-filter> 3 <action android:name="android.intent.action.MAIN" /> 4 <category android:name="android.intent.category.LAUNCHER" /> 5 </intent-filter> 6</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.