-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainActivity.java
285 lines (248 loc) · 13.1 KB
/
MainActivity.java
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package com.uid2.dev;
import static com.uid2.dev.utils.BundleExKt.isEnvironmentEUID;
import static com.uid2.dev.utils.ContextExKt.getMetadata;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.MediaController;
import android.widget.VideoView;
import androidx.appcompat.app.AppCompatActivity;
import com.google.ads.interactivemedia.v3.api.AdDisplayContainer;
import com.google.ads.interactivemedia.v3.api.AdErrorEvent;
import com.google.ads.interactivemedia.v3.api.AdEvent;
import com.google.ads.interactivemedia.v3.api.AdsLoader;
import com.google.ads.interactivemedia.v3.api.AdsManager;
import com.google.ads.interactivemedia.v3.api.AdsManagerLoadedEvent;
import com.google.ads.interactivemedia.v3.api.AdsRenderingSettings;
import com.google.ads.interactivemedia.v3.api.AdsRequest;
import com.google.ads.interactivemedia.v3.api.ImaSdkFactory;
import com.google.ads.interactivemedia.v3.api.ImaSdkSettings;
import com.google.ads.interactivemedia.v3.api.player.VideoProgressUpdate;
import com.uid2.EUIDManager;
import com.uid2.UID2Manager;
import com.uid2.data.UID2Identity;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
/**
* Porting of Google's BasicExample
* <a href="https://github.com/googleads/googleads-ima-android/tree/main/basicexample">BasicExample</a>
*/
public class MainActivity extends AppCompatActivity {
private static final String LOGTAG = "IMABasicSample";
private static final String SAMPLE_VIDEO_URL =
"https://storage.googleapis.com/gvabox/media/samples/stock.mp4";
/**
* IMA sample tag for a single skippable inline video ad. See more IMA sample tags at
* <a href="https://developers.google.com/interactive-media-ads/docs/sdks/html5/client-side/tags">Client Side Tags</a>
*/
private static final String SAMPLE_VAST_TAG_URL =
"https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/"
+ "single_preroll_skippable&sz=640x480&ciu_szs=300x250%2C728x90&gdfp_req=1&output=vast"
+ "&unviewed_position_start=1&env=vp&impl=s&correlator=";
// Factory class for creating SDK objects.
private ImaSdkFactory sdkFactory;
// The AdsLoader instance exposes the requestAds method.
private AdsLoader adsLoader;
// AdsManager exposes methods to control ad playback and listen to ad events.
private AdsManager adsManager;
// The saved content position, used to resumed content following an ad break.
private int savedPosition = 0;
// This sample uses a VideoView for content and ad playback. For production apps, Android's Exoplayer offers
// a more fully featured player compared to the VideoView.
private VideoView videoPlayer;
private MediaController mediaController;
private View playButton;
private VideoAdPlayerAdapter videoAdPlayerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// Load UID2Identity to test with
loadUID2Identity();
// Create the UI for controlling the video view.
mediaController = new MediaController(this);
videoPlayer = findViewById(R.id.videoView);
mediaController.setAnchorView(videoPlayer);
videoPlayer.setMediaController(mediaController);
// Create an ad display container that uses a ViewGroup to listen to taps.
ViewGroup videoPlayerContainer = findViewById(R.id.videoPlayerContainer);
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
videoAdPlayerAdapter = new VideoAdPlayerAdapter(videoPlayer, audioManager);
sdkFactory = ImaSdkFactory.getInstance();
AdDisplayContainer adDisplayContainer =
ImaSdkFactory.createAdDisplayContainer(videoPlayerContainer, videoAdPlayerAdapter);
// Create an AdsLoader.
ImaSdkSettings settings = sdkFactory.createImaSdkSettings();
adsLoader = sdkFactory.createAdsLoader(this, settings, adDisplayContainer);
// Add listeners for when ads are loaded and for errors.
adsLoader.addAdErrorListener(
new AdErrorEvent.AdErrorListener() {
/** An event raised when there is an error loading or playing ads. */
@Override
public void onAdError(AdErrorEvent adErrorEvent) {
Log.i(LOGTAG, "Ad Error: " + adErrorEvent.getError().getMessage());
resumeContent();
}
});
adsLoader.addAdsLoadedListener(
new AdsLoader.AdsLoadedListener() {
@Override
public void onAdsManagerLoaded(AdsManagerLoadedEvent adsManagerLoadedEvent) {
// Ads were successfully loaded, so get the AdsManager instance. AdsManager has
// events for ad playback and errors.
adsManager = adsManagerLoadedEvent.getAdsManager();
// Attach event and error event listeners.
adsManager.addAdErrorListener(
new AdErrorEvent.AdErrorListener() {
/** An event raised when there is an error loading or playing ads. */
@Override
public void onAdError(AdErrorEvent adErrorEvent) {
Log.e(LOGTAG, "Ad Error: " + adErrorEvent.getError().getMessage());
String universalAdIds =
Arrays.toString(adsManager.getCurrentAd().getUniversalAdIds());
Log.i(
LOGTAG,
"Discarding the current ad break with universal "
+ "ad Ids: "
+ universalAdIds);
adsManager.discardAdBreak();
}
});
adsManager.addAdEventListener(
new AdEvent.AdEventListener() {
/** Responds to AdEvents. */
@Override
public void onAdEvent(AdEvent adEvent) {
if (adEvent.getType() != AdEvent.AdEventType.AD_PROGRESS) {
Log.i(LOGTAG, "Event: " + adEvent.getType());
}
// These are the suggested event types to handle. For full list of all ad event types,
// see AdEvent.AdEventType documentation.
switch (adEvent.getType()) {
case LOADED:
// AdEventType.LOADED is fired when ads are ready to play.
// This sample app uses the sample tag single_preroll_skippable_ad_tag_url
// that requires calling AdsManager.start() to start ad playback. If you use
// a different ad tag URL that returns a VMAP or an ad rules playlist,
// the adsManager.init() function will trigger ad playback automatically and
// the IMA SDK will ignore the adsManager.start(). It is safe to always call
// adsManager.start() in the LOADED event.
adsManager.start();
break;
case CONTENT_PAUSE_REQUESTED:
// AdEventType.CONTENT_PAUSE_REQUESTED is fired when you
// should pause your content and start playing an ad.
pauseContentForAds();
break;
case CONTENT_RESUME_REQUESTED:
// AdEventType.CONTENT_RESUME_REQUESTED is fired when the ad
// you should play your content.
resumeContent();
break;
case ALL_ADS_COMPLETED:
// Calling adsManager.destroy() triggers the function
// VideoAdPlayer.release().
adsManager.destroy();
adsManager = null;
break;
case CLICKED:
// When the user clicks on the Learn More button, the IMA SDK fires
// this event, pauses the ad, and opens the ad's click-through URL.
// When the user returns to the app, the IMA SDK calls the
// VideoAdPlayer.playAd() function automatically.
break;
default:
break;
}
}
});
AdsRenderingSettings adsRenderingSettings =
ImaSdkFactory.getInstance().createAdsRenderingSettings();
adsManager.init(adsRenderingSettings);
}
});
// When the play button is clicked, request ads and hide the button.
playButton = findViewById(R.id.playButton);
playButton.setOnClickListener(
view -> {
videoPlayer.setVideoPath(SAMPLE_VIDEO_URL);
requestAds(SAMPLE_VAST_TAG_URL);
view.setVisibility(View.GONE);
});
}
private void loadUID2Identity() {
InputStream is = getResources().openRawResource(R.raw.uid2identity);
StringBuilder text = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
String jsonString = text.toString();
JSONObject jsonObject = new JSONObject(jsonString);
UID2Identity fromJsonIdentity = UID2Identity.Companion.fromJson(jsonObject);
// Emulate A UID2Identity With Valid Times
long now = System.currentTimeMillis();
long identityExpires = now * 60 * 60;
long refreshFrom = now * 60 * 40;
long refreshExpires = now * 60 * 80;
UID2Identity identity = new UID2Identity(fromJsonIdentity.getAdvertisingToken(),
fromJsonIdentity.getRefreshToken(),
identityExpires,
refreshFrom,
refreshExpires,
fromJsonIdentity.getRefreshResponseKey());
if (isEnvironmentEUID(getMetadata(getBaseContext()))) {
EUIDManager.getInstance().setIdentity(identity);
} else {
UID2Manager.getInstance().setIdentity(identity);
}
} catch (Exception e) {
Log.e(LOGTAG, "Error loading Identity: " + e);
}
}
private void pauseContentForAds() {
Log.i(LOGTAG, "pauseContentForAds");
savedPosition = videoPlayer.getCurrentPosition();
videoPlayer.stopPlayback();
// Hide the buttons and seek bar controlling the video view.
videoPlayer.setMediaController(null);
}
private void resumeContent() {
Log.i(LOGTAG, "resumeContent");
// Show the buttons and seek bar controlling the video view.
videoPlayer.setVideoPath(SAMPLE_VIDEO_URL);
videoPlayer.setMediaController(mediaController);
videoPlayer.setOnPreparedListener(
mediaPlayer -> {
if (savedPosition > 0) {
mediaPlayer.seekTo(savedPosition);
}
mediaPlayer.start();
});
videoPlayer.setOnCompletionListener(
mediaPlayer -> videoAdPlayerAdapter.notifyImaOnContentCompleted());
}
private void requestAds(String adTagUrl) {
// Create the ads request.
AdsRequest request = sdkFactory.createAdsRequest();
request.setAdTagUrl(adTagUrl);
request.setContentProgressProvider(
() -> {
if (videoPlayer.getDuration() <= 0) {
return VideoProgressUpdate.VIDEO_TIME_NOT_READY;
}
return new VideoProgressUpdate(
videoPlayer.getCurrentPosition(), videoPlayer.getDuration());
});
// Request the ad. After the ad is loaded, onAdsManagerLoaded() will be called.
adsLoader.requestAds(request);
}
}