Overview

Splash ads are displayed immediately after an app is launched, even before the home screen of the app is displayed.
This codelab will step you through the process of adding a splash ad and correctly displaying it in your app.

What You Will Create

In this codelab, you will build an empty app and integrate a splash ad into it. Your app will:

What You Will Learn

In this codelab, you will learn how to:

Hardware Requirements

Software Requirements

To view the HMS Core (APK) version on a device, go to Settings > Apps > Apps and search for HMS Core.

Creating a Project in Android Studio

  1. Start Android Studio.
  2. Start a new project, select Empty Activity, and name the project SplashAdExample.
  3. Click Finish.

Configuring the HUAWEI Ads SDK Repository and Dependency Package

Configure the Maven repository address in the project-level build.gradle file.

buildscript { repositories { google() jcenter() maven { url 'https://developer.huawei.com/repo/' } } ... } allprojects { repositories { google() jcenter() maven {url 'https://developer.huawei.com/repo/'} } }

Configure the dependency package in the app-level build.gradle file, and replace {version} with the latest version of HUAWEI Ads SDK. For details, please refer to Version Change History.

dependencies { ... implementation 'com.huawei.hms:ads-lite:{version}' ... }

Click Sync Now and wait until synchronization is complete.

Configuring Obfuscation Scripts

Before building the APK, configure obfuscation scripts to prevent the HUAWEI Ads SDK from being obfuscated. If obfuscation arises, the HUAWEI Ads SDK may not function properly.

  1. Open the obfuscation script file of your Android project.
  2. Add the following two lines of code to the app/proguard-rules.pro file to exclude the HUAWEI Ads SDK from obfuscation:
    -keep class com.huawei.openalliance.ad.** { *; } -keep class com.huawei.hms.ads.** { *; }

The HUAWEI Ads SDK provides the SplashView class for loading and displaying a splash ad.
In this codelab, you will use a layout XML file to set the layouts. To save time, use the XML file content that has been created.
Create the activity_splash.xml file in the res/layout/ directory and add the following XML content to the file:
activity_splash.xml

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".SplashActivity"> <RelativeLayout android:id="@+id/logo" android:layout_width="fill_parent" android:layout_height="100dp" android:layout_alignParentBottom="true" android:background="@android:color/white" android:visibility="visible"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginBottom="39dp" android:orientation="vertical"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginBottom="6dp" android:gravity="center" android:orientation="horizontal"> <ImageView android:layout_width="28dp" android:layout_height="28dp" android:background="@mipmap/ic_launcher" /> <View android:layout_width="0.5dp" android:layout_height="18dp" android:layout_marginLeft="12dp" android:layout_marginRight="12dp" android:alpha="0.1" android:background="#000000" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:alpha="1" android:text="@string/owner" android:textColor="#000000" android:textSize="16sp" /> </LinearLayout> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:alpha="0.5" android:text="@string/copyright_info" android:textColor="#000000" android:textSize="8sp" /> </LinearLayout> </RelativeLayout> <com.huawei.hms.ads.splash.SplashView android:id="@+id/splash_ad_view" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@id/logo" /> </RelativeLayout>

Add the following content to the res/values/strings.xml file:
strings.xml

<resources> ... <string name="ad_id_splash">testq6zq98hecj</string> <string name="owner">HUAWEI Developer</string> <string name="copyright_info">Copyright 2020. Huawei Technologies Co., Ltd</string> <string name="status_load_ad_success">Ad loading state: loaded successfully.</string> <string name="status_load_ad_fail">Ad loading state: failed to be loaded. Error code: </string> <string name="status_ad_dismissed">Ad is dismissed.</string> ... </resources>

Creating an Activity Class of the Splash Ad
You need to create a SplashActivity.java class to load and display a splash ad. The content is as follows:
SplashActivity.java

import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; public class SplashActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); } }

Initializing the HUAWEI Ads SDK
To obtain ads using the HUAWEI Ads SDK, your app must initialize the SDK when starting up.
Call HwAds.init() in the onCreate() method of the SplashActivity class to initialize the HUAWEI Ads SDK.
SplashActivity.java

import com.huawei.hms.ads.HwAds; ... public class SplashActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); // Initialize the HUAWEI Ads SDK. HwAds.init(this); ... } ... }

Modifying the AndroidManifest.xml File
Modify the AndroidManifest.xml file by changing the activity started by default to SplashActivity. In this way, a splash ad can be displayed before your app's home screen is loaded. The file content after modification is as follows:
AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="***"> <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/AppTheme"> <activity android:name=".MainActivity"> </activity> <activity android:name=".SplashActivity" android:exported="true" android:screenOrientation="portrait"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>

Use the load method of the SplashView class to load a splash ad. When calling this method, you can set the ad slot ID, screen orientation, ad parameter, and ad loading listener. You can also use the setAdDisplayListener method to set the ad display listener. The complete code is as follows:
SplashActivity.java

import android.content.Intent; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.huawei.hms.ads.AdParam; import com.huawei.hms.ads.AudioFocusType; import com.huawei.hms.ads.HwAds; import com.huawei.hms.ads.splash.SplashAdDisplayListener; import com.huawei.hms.ads.splash.SplashView; public class SplashActivity extends AppCompatActivity { private static final String TAG = SplashActivity.class.getSimpleName(); // Ad display timeout interval, in milliseconds. private static final int AD_TIMEOUT = 5000; // Ad display timeout message flag. private static final int MSG_AD_TIMEOUT = 1001; /** * Pause flag. * On the splash ad screen: * Set this parameter to true when exiting the app to ensure that the app home screen is not displayed. * Set this parameter to false when returning to the splash ad screen from another screen to ensure that the app home screen can be displayed properly. */ private boolean hasPaused = false; // Callback handler used when the ad display timeout message is received. private Handler timeoutHandler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(@NonNull Message msg) { if (SplashActivity.this.hasWindowFocus()) { jump(); } return false; } }); private SplashView splashView; private SplashView.SplashAdLoadListener splashAdLoadListener = new SplashView.SplashAdLoadListener() { @Override public void onAdLoaded() { // Call this method when an ad is successfully loaded. Log.i(TAG, "SplashAdLoadListener onAdLoaded."); Toast.makeText(SplashActivity.this, getString(R.string.status_load_ad_success), Toast.LENGTH_SHORT).show(); } @Override public void onAdFailedToLoad(int errorCode) { // Call this method when an ad fails to be loaded. Log.i(TAG, "SplashAdLoadListener onAdFailedToLoad, errorCode: " + errorCode); Toast.makeText(SplashActivity.this, getString(R.string.status_load_ad_fail) + errorCode, Toast.LENGTH_SHORT).show(); jump(); } @Override public void onAdDismissed() { // Call this method when the ad display is complete. Log.i(TAG, "SplashAdLoadListener onAdDismissed."); Toast.makeText(SplashActivity.this, getString(R.string.status_ad_dismissed), Toast.LENGTH_SHORT).show(); jump(); } }; private SplashAdDisplayListener adDisplayListener = new SplashAdDisplayListener() { @Override public void onAdShowed() { // Call this method when an ad is displayed. Log.i(TAG, "SplashAdDisplayListener onAdShowed."); } @Override public void onAdClick() { // Call this method when an ad is clicked. Log.i(TAG, "SplashAdDisplayListener onAdClick."); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); // Initialize the HUAWEI Ads SDK. HwAds.init(this); loadAd(); } private void loadAd() { Log.i(TAG, "Start to load ad"); AdParam adParam = new AdParam.Builder().build(); splashView = findViewById(R.id.splash_ad_view); splashView.setAdDisplayListener(adDisplayListener); // Set a logo image. splashView.setLogoResId(R.mipmap.ic_launcher); // Set logo description. splashView.setMediaNameResId(R.string.app_name); // Set the audio focus type for a video splash ad. splashView.setAudioFocusType(AudioFocusType.NOT_GAIN_AUDIO_FOCUS_WHEN_MUTE); splashView.load(getString(R.string.ad_id_splash), ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, adParam, splashAdLoadListener); Log.i(TAG, "End to load ad"); // Remove the timeout message from the message queue. timeoutHandler.removeMessages(MSG_AD_TIMEOUT); // Send a delay message to ensure that the app home screen can be displayed when the ad display times out. timeoutHandler.sendEmptyMessageDelayed(MSG_AD_TIMEOUT, AD_TIMEOUT); } /** * Switch from the splash ad screen to the app home screen when the ad display is complete. */ private void jump() { Log.i(TAG, "jump hasPaused: " + hasPaused); if (!hasPaused) { hasPaused = true; Log.i(TAG, "jump into application"); startActivity(new Intent(SplashActivity.this, MainActivity.class)); Handler mainHandler = new Handler(); mainHandler.postDelayed(new Runnable() { @Override public void run() { finish(); } }, 1000); } } /** * Set this parameter to true when exiting the app to ensure that the app home screen is not displayed. */ @Override protected void onStop() { Log.i(TAG, "SplashActivity onStop."); // Remove the timeout message from the message queue. timeoutHandler.removeMessages(MSG_AD_TIMEOUT); hasPaused = true; super.onStop(); } /** * Call this method when returning to the splash ad screen from another screen to access the app home screen. */ @Override protected void onRestart() { Log.i(TAG, "SplashActivity onRestart."); super.onRestart(); hasPaused = false; jump(); } @Override protected void onDestroy() { Log.i(TAG, "SplashActivity onDestroy."); super.onDestroy(); if (splashView != null) { splashView.destroyView(); } } @Override protected void onPause() { Log.i(TAG, "SplashActivity onPause."); super.onPause(); if (splashView != null) { splashView.pauseView(); } } @Override protected void onResume() { Log.i(TAG, "SplashActivity onResume."); super.onResume(); if (splashView != null) { splashView.resumeView(); } } }

After running the project, you will see the splash ad in your app.

Well done. You have successfully completed this codelab and learned how to:

For more information, please click the following links:

You can click the button below to download the source code.

Download source code

Code copied