开屏广告是一种在应用启动时且在应用主界面显示之前展示的广告。
此Codelab将引导您在应用中增加开屏广告的展示。在整个过程中,将介绍添加代码的详细过程以正确展示开屏广告。
您将构建一个展示开屏广告的应用。您的应用将:
在项目级build.gradle
文件中配置Maven仓库路径,需添加下面内容:
buildscript {
repositories {
google()
jcenter()
maven { url 'https://developer.huawei.com/repo/' }
}
...
}
allprojects {
repositories {
google()
jcenter()
maven { url 'https://developer.huawei.com/repo/' }
}
}
在应用级build.gradle
文件中配置依赖包,需添加下面内容,并将{version}
替换为最新HUAWEI Ads SDK版本号,参见版本更新说明。
dependencies {
...
implementation 'com.huawei.hms:ads-lite:{version}'
...
}
点击"Sync Now"等待同步完成。
开发者编译APK前需要配置不要混淆HUAWEI Ads SDK,避免功能异常。
app/proguard-rules.pro
文件中添加如下两行代码,配置排除HUAWEI Ads SDK的混淆。-keep class com.huawei.openalliance.ad.** { *; }
-keep class com.huawei.hms.ads.** { *; }
对于开屏广告,HUAWEI Ads SDK提供了广告视图类SplashView
,用于获取和展示开屏广告。
现在,您将使用布局XML文件方式设置开屏广告视图的布局。为了节省时间,您可以使用下面创建好的XML内容。
接下来,你需要在res/layout/
目录下新增activity_splash.xml
文件,并在文件中添加以下列出的XML内容。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>
同时,需要在res/values/strings.xml
中增加下面内容。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>
你需要创建SplashActivity.java
类,用于实现开屏广告获取和展示。内容如下: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);
}
}
要借助于HUAWEI Ads SDK获取广告,必须先在您的应用中调用HwAds.init()
方法初始化SDK ,此过程需要在应用程序启动时完成,在应用后续运行过程中无需重复执行此过程。
在SplashActivity
类的onCreate()
方法中调用HwAds.init()
以执行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);
// 初始化 HUAWEI Ads SDK
HwAds.init(this);
...
}
...
}
您需将默认启动的activity修改为SplashActivity
,这样即可在应用主界面加载前展示开屏广告。修改后的内容如下: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>
您将使用SplashView
类的load方法
获取开屏广告,在调用时可设置广告位ID、设置屏幕方向、设置广告参数和广告加载状态监听器。还可通过setAdDisplayListener
方法设置广告展示状态监听器。完整代码如下。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();
// 广告展示超时时间:单位毫秒
private static final int AD_TIMEOUT = 5000;
// 广告展示超时消息标记
private static final int MSG_AD_TIMEOUT = 1001;
/**
* 暂停标志位。
* 在开屏广告页面展示时:
* 按返回键退出应用时需设置为true,以确保应用主界面不被拉起;
* 从其他页面回到开屏广告页面时需设置为false,以确保仍然可以正常跳转至应用主界面。
*/
private boolean hasPaused = false;
// 广告展示超时消息回调handler
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() {
// 广告展示完毕时调用
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() {
// 广告显示时调用
Log.i(TAG, "SplashAdDisplayListener onAdShowed.");
}
@Override
public void onAdClick() {
// 广告被点击时调用
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);
// 设置logo图片
splashView.setLogoResId(R.mipmap.ic_launcher);
// 设置logo描述
splashView.setMediaNameResId(R.string.app_name);
// 设置视频类开屏广告的音频焦点类型
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");
// 移除消息队列中等待的超时消息
timeoutHandler.removeMessages(MSG_AD_TIMEOUT);
// 发送延迟消息,用来处理广告展示超时时,能够正常跳转至应用主界面。
timeoutHandler.sendEmptyMessageDelayed(MSG_AD_TIMEOUT, AD_TIMEOUT);
}
/**
* 广告展示完毕时,从广告界面跳转至应用主界面
*/
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);
}
}
/**
* 按返回键退出应用时需设置为true,以确保应用主界面不被拉起
*/
@Override
protected void onStop() {
Log.i(TAG, "SplashActivity onStop.");
// 移除消息队列中等待的超时消息
timeoutHandler.removeMessages(MSG_AD_TIMEOUT);
hasPaused = true;
super.onStop();
}
/**
* 从其他页面回到开屏页面时调用,进入应用主界面
*/
@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();
}
}
}
运行项目后,您将会在应用中看到开屏广告。
祝贺您,您已经成功完成了Codelab并学到了:
您可以阅读下面链接,了解更多相关的信息。
源码下载地址如下: