-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathAppOpenAdController.cs
More file actions
223 lines (197 loc) · 7.77 KB
/
AppOpenAdController.cs
File metadata and controls
223 lines (197 loc) · 7.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
using System;
using UnityEngine;
using GoogleMobileAds.Api;
using GoogleMobileAds.Common;
namespace GoogleMobileAds.Sample
{
/// <summary>
/// Demonstrates how to use Google Mobile Ads app open ads.
/// </summary>
[AddComponentMenu("GoogleMobileAds/Samples/AppOpenAdController")]
public class AppOpenAdController : MonoBehaviour
{
/// <summary>
/// UI element activated when an ad is ready to show.
/// </summary>
public GameObject AdLoadedStatus;
// These ad units are configured to always serve test ads.
#if UNITY_ANDROID
private const string _adUnitId = "ca-app-pub-3940256099942544/9257395921";
#elif UNITY_IPHONE
private const string _adUnitId = "ca-app-pub-3940256099942544/5575463023";
#else
private const string _adUnitId = "unused";
#endif
// App open ads can be preloaded for up to 4 hours.
private readonly TimeSpan TIMEOUT = TimeSpan.FromHours(4);
private DateTime _expireTime;
private AppOpenAd _appOpenAd;
private void Awake()
{
// Use the AppStateEventNotifier to listen to application open/close events.
// This is used to launch the loaded ad when we open the app.
AppStateEventNotifier.AppStateChanged += OnAppStateChanged;
}
private void OnDestroy()
{
// Always unlisten to events when complete.
AppStateEventNotifier.AppStateChanged -= OnAppStateChanged;
}
/// <summary>
/// Loads the ad.
/// </summary>
public void LoadAd()
{
// Clean up the old ad before loading a new one.
if (_appOpenAd != null)
{
DestroyAd();
}
Debug.Log("Loading app open ad.");
// Create our request used to load the ad.
var adRequest = new AdRequest();
// Send the request to load the ad.
AppOpenAd.Load(_adUnitId, adRequest, (AppOpenAd ad, LoadAdError error) =>
{
// If the operation failed with a reason.
if (error != null)
{
Debug.LogError("App open ad failed to load an ad with error : "
+ error);
return;
}
// If the operation failed for unknown reasons.
// This is an unexpected error, please report this bug if it happens.
if (ad == null)
{
Debug.LogError("Unexpected error: App open ad load event fired with " +
" null ad and null error.");
return;
}
// The operation completed successfully.
Debug.Log("App open ad loaded with response : " + ad.GetResponseInfo());
_appOpenAd = ad;
// App open ads can be preloaded for up to 4 hours.
_expireTime = DateTime.Now + TIMEOUT;
// Register to ad events to extend functionality.
RegisterEventHandlers(ad);
// Inform the UI that the ad is ready.
// Use MobileAdsEventExecutor to ensure the UI is updated on the main thread.
MobileAdsEventExecutor.ExecuteInUpdate(() =>
{
AdLoadedStatus?.SetActive(true);
});
});
}
/// <summary>
/// Shows the ad.
/// </summary>
public void ShowAd()
{
// App open ads can be preloaded for up to 4 hours.
if (_appOpenAd != null && _appOpenAd.CanShowAd() && DateTime.Now < _expireTime)
{
Debug.Log("Showing app open ad.");
_appOpenAd.Show();
}
else
{
Debug.LogError("App open ad is not ready yet.");
}
// Inform the UI that the ad is not ready.
AdLoadedStatus?.SetActive(false);
}
/// <summary>
/// Destroys the ad.
/// </summary>
public void DestroyAd()
{
if (_appOpenAd != null)
{
Debug.Log("Destroying app open ad.");
_appOpenAd.Destroy();
_appOpenAd = null;
}
// Inform the UI that the ad is not ready.
AdLoadedStatus?.SetActive(false);
}
/// <summary>
/// Logs the ResponseInfo.
/// </summary>
public void LogResponseInfo()
{
if (_appOpenAd != null)
{
var responseInfo = _appOpenAd.GetResponseInfo();
UnityEngine.Debug.Log(responseInfo);
}
}
private void OnAppStateChanged(AppState state)
{
Debug.Log("App State changed to : " + state);
// If the app is Foregrounded and the ad is available, show it.
if (state == AppState.Foreground)
{
ShowAd();
}
}
private void RegisterEventHandlers(AppOpenAd ad)
{
// Raised when the ad is estimated to have earned money.
ad.OnAdPaid += (AdValue adValue) =>
{
// This log is executed off the Unity main thread.
// Write all time-sensitive code before ExecuteInUpdate().
Debug.Log(String.Format("App open ad paid {0} {1}.",
adValue.Value,
adValue.CurrencyCode));
MobileAdsEventExecutor.ExecuteInUpdate(() =>
{
// This callback may be delayed on Android until the user
// returns to the app. Place all code that interacts with
// Unity UI and GameObjects inside this callback.
Debug.Log("App open ad paid callback " +
"invoked inside ExecuteInUpdate.");
});
};
// Raised when an impression is recorded for an ad.
ad.OnAdImpressionRecorded += () =>
{
Debug.Log("App open ad recorded an impression.");
};
// Raised when a click is recorded for an ad.
ad.OnAdClicked += () =>
{
Debug.Log("App open ad was clicked.");
};
// Raised when an ad opened full screen content.
ad.OnAdFullScreenContentOpened += () =>
{
Debug.Log("App open ad full screen content opened.");
// Use MobileAdsEventExecutor to ensure the UI is updated on the main thread.
MobileAdsEventExecutor.ExecuteInUpdate(() =>
{
AdLoadedStatus?.SetActive(false);
});
};
// Raised when the ad closed full screen content.
ad.OnAdFullScreenContentClosed += () =>
{
Debug.Log("App open ad full screen content closed.");
// It may be useful to load a new ad when the current one is complete.
LoadAd();
};
// Raised when the ad failed to open full screen content.
ad.OnAdFullScreenContentFailed += (AdError error) =>
{
Debug.LogError("App open ad failed to open full screen content with error : "
+ error);
// Use MobileAdsEventExecutor to ensure the UI is updated on the main thread.
MobileAdsEventExecutor.ExecuteInUpdate(() =>
{
AdLoadedStatus?.SetActive(false);
});
};
}
}
}