在 Android 中实现插屏广告
要使用 UnityAds
API 显示全屏插屏广告
插屏广告示例
在此示例中,您可以从游戏中的任何地方调用 DisplayInterstitialAd
来显示插屏广告,只要 Unity Ads 已成功初始化。
Note: Unity Ads requires access to the currently running Activity, so the following example uses getApplicationContext()
. Because this might not be suitable for all implementations, some customization might be required (depending on the integration).
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import com.unity3d.ads.IUnityAdsLoadListener;
import com.unity3d.ads.IUnityAdsShowListener;
import com.unity3d.ads.UnityAdsShowOptions;
import com.unity3d.ads.example.R;
import com.unity3d.ads.IUnityAdsInitializationListener;
import com.unity3d.ads.UnityAds;
public class ShowInterstitialAd extends AppCompatActivity implements IUnityAdsInitializationListener {
private String unityGameID = "1234567";
private Boolean testMode = true;
private String adUnitId = "video";
private IUnityAdsLoadListener loadListener = new IUnityAdsLoadListener() {
@Override
public void onUnityAdsAdLoaded(String placementId) {
UnityAds.show((Activity)getApplicationContext(), adUnitId, new UnityAdsShowOptions(), showListener);
}
@Override
public void onUnityAdsFailedToLoad(String placementId, UnityAds.UnityAdsLoadError error, String message) {
Log.e("UnityAdsExample", "Unity Ads failed to load ad for " + placementId + " with error: [" + error + "] " + message);
}
};
private IUnityAdsShowListener showListener = new IUnityAdsShowListener() {
@Override
public void onUnityAdsShowFailure(String placementId, UnityAds.UnityAdsShowError error, String message) {
Log.e("UnityAdsExample", "Unity Ads failed to show ad for " + placementId + " with error: [" + error + "] " + message);
}
@Override
public void onUnityAdsShowStart(String placementId) {
Log.v("UnityAdsExample", "onUnityAdsShowStart: " + placementId);
}
@Override
public void onUnityAdsShowClick(String placementId) {
Log.v("UnityAdsExample", "onUnityAdsShowClick: " + placementId);
}
@Override
public void onUnityAdsShowComplete(String placementId, UnityAds.UnityAdsShowCompletionState state) {
Log.v("UnityAdsExample", "onUnityAdsShowComplete: " + placementId);
}
};
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
// Initialize the SDK:
UnityAds.initialize(getApplicationContext(), unityGameID, testMode, this);
}
@Override
public void onInitializationComplete() {
DisplayInterstitialAd();
}
@Override
public void onInitializationFailed(UnityAds.UnityAdsInitializationError error, String message) {
Log.e("UnityAdsExample", "Unity Ads initialization failed with error: [" + error + "] " + message);
}
// Implement a function to load an interstitial ad. The ad will start to show after the ad has been loaded.
public void DisplayInterstitialAd () {
UnityAds.load(adUnitId, loadListener);
}
}
下一步:要改进您的实现,请参考 在 Android 中实现奖励广告 文档。