Skip to content

Commit

Permalink
Added UMP SDK integration to Ad Manager Banner Java & Kotlin samples
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 557119541
  • Loading branch information
Justin Malandruccolo authored and maddevrelgithubbot committed Aug 15, 2023
1 parent 861b463 commit 6c32363
Show file tree
Hide file tree
Showing 15 changed files with 397 additions and 62 deletions.
1 change: 1 addition & 0 deletions java/admanager/BannerExample/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,5 @@ android {
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.gms:play-services-ads:22.2.0'
implementation 'com.google.android.ump:user-messaging-platform:2.1.0'
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package com.google.android.gms.example.bannerexample;

import android.app.Activity;
import androidx.annotation.NonNull;
import com.google.android.ump.ConsentDebugSettings;
import com.google.android.ump.ConsentForm.OnConsentFormDismissedListener;
import com.google.android.ump.ConsentInformation;
import com.google.android.ump.ConsentInformation.PrivacyOptionsRequirementStatus;
import com.google.android.ump.ConsentRequestParameters;
import com.google.android.ump.FormError;
import com.google.android.ump.UserMessagingPlatform;

/**
* The Google Mobile Ads SDK provides the User Messaging Platform (Google's
* IAB Certified consent management platform) as one solution to capture
* consent for users in GDPR impacted countries. This is an example and
* you can choose another consent management platform to capture consent.
*/
public class GoogleMobileAdsConsentManager {
private final Activity activity;
private final ConsentInformation consentInformation;

/** Interface definition for a callback to be invoked when consent gathering is complete. */
public interface OnConsentGatheringCompleteListener {
void consentGatheringComplete(FormError error);
}

/** Constructor */
public GoogleMobileAdsConsentManager(@NonNull Activity activity) {
this.activity = activity;
this.consentInformation = UserMessagingPlatform.getConsentInformation(activity);
}

/** Helper variable to determine if the app can request ads. */
public boolean canRequestAds() {
return consentInformation.canRequestAds();
}

/** Helper variable to determine if the privacy options form is required. */
public boolean isPrivacyOptionsRequired() {
return consentInformation.getPrivacyOptionsRequirementStatus()
== PrivacyOptionsRequirementStatus.REQUIRED;
}

/** Helper method to call the UMP SDK methods to request consent information and load/present a
* consent form if necessary. */
public void gatherConsent(
OnConsentGatheringCompleteListener onConsentGatheringCompleteListener) {
// For testing purposes, you can force a DebugGeography of EEA or NOT_EEA.
ConsentDebugSettings debugSettings = new ConsentDebugSettings.Builder(activity)
// .setDebugGeography(ConsentDebugSettings.DebugGeography.DEBUG_GEOGRAPHY_EEA)
// Check your logcat output for the hashed device ID e.g.
// "Use new ConsentDebugSettings.Builder().addTestDeviceHashedId("ABCDEF012345")" to use
// the debug functionality.
.addTestDeviceHashedId("TEST-DEVICE-HASHED-ID")
.build();

ConsentRequestParameters params = new ConsentRequestParameters.Builder()
.setConsentDebugSettings(debugSettings)
.build();

// Requesting an update to consent information should be called on every app launch.
consentInformation.requestConsentInfoUpdate(
activity,
params,
() ->
UserMessagingPlatform.loadAndShowConsentFormIfRequired(
activity,
formError -> {
// Consent has been gathered.
onConsentGatheringCompleteListener.consentGatheringComplete(formError);
}),
requestConsentError ->
onConsentGatheringCompleteListener.consentGatheringComplete(requestConsentError)
);
}

/** Helper method to call the UMP SDK method to present the privacy options form. */
public void showPrivacyOptionsForm(
Activity activity,
OnConsentFormDismissedListener onConsentFormDismissedListener) {
UserMessagingPlatform.showPrivacyOptionsForm(activity, onConsentFormDismissedListener);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,80 +18,151 @@
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu;
import android.widget.Toast;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.RequestConfiguration;
import com.google.android.gms.ads.admanager.AdManagerAdRequest;
import com.google.android.gms.ads.admanager.AdManagerAdView;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;

/**
* Main Activity. Inflates main activity xml and child fragments.
*/
public class MyActivity extends AppCompatActivity {

private AdManagerAdView adView;
private static final String TAG = "MyActivity";
private final AtomicBoolean isMobileAdsInitializeCalled = new AtomicBoolean(false);
private AdManagerAdView adView;
private GoogleMobileAdsConsentManager googleMobileAdsConsentManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);

// Gets the ad view defined in layout/ad_fragment.xml with ad unit ID set in
// values/strings.xml.
adView = findViewById(R.id.ad_view);

// Set your test devices. Check your logcat output for the hashed device ID to
// get test ads on a physical device. e.g.
// "Use RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("ABCDEF012345"))
// to get test ads on this device."
MobileAds.setRequestConfiguration(
new RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("ABCDEF012345"))
.build());

// Log the Mobile Ads SDK version.
Log.d(TAG, "Google Mobile Ads SDK Version: " + MobileAds.getVersion());

// Initialize the Mobile Ads SDK.
MobileAds.initialize(
this,
new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus status) {}
});
// Create an ad request.
AdManagerAdRequest adRequest = new AdManagerAdRequest.Builder().build();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);

// Gets the ad view defined in layout/ad_fragment.xml with ad unit ID set in
// values/strings.xml.
adView = findViewById(R.id.ad_view);

// Set your test devices. Check your logcat output for the hashed device ID to
// get test ads on a physical device. e.g.
// "Use RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("ABCDEF012345"))
// to get test ads on this device."
MobileAds.setRequestConfiguration(
new RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("ABCDEF012345")).build());

// Log the Mobile Ads SDK version.
Log.d(TAG, "Google Mobile Ads SDK Version: " + MobileAds.getVersion());

googleMobileAdsConsentManager = new GoogleMobileAdsConsentManager(this);

googleMobileAdsConsentManager.gatherConsent(
consentError -> {
if (consentError != null) {
// Consent not obtained in current session.
Log.w(
TAG,
String.format("%s: %s", consentError.getErrorCode(), consentError.getMessage()));
}

if (googleMobileAdsConsentManager.canRequestAds()) {
initializeMobileAdsSdk();
}

// Start loading the ad in the background.
adView.loadAd(adRequest);
if (googleMobileAdsConsentManager.isPrivacyOptionsRequired()) {
// Regenerate the options menu to include a privacy setting.
invalidateOptionsMenu();
}
});

// This sample attempts to load ads using consent obtained in the previous session.
if (googleMobileAdsConsentManager.canRequestAds()) {
initializeMobileAdsSdk();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.action_menu, menu);
MenuItem moreMenu = menu.findItem(R.id.action_more);
moreMenu.setVisible(googleMobileAdsConsentManager.isPrivacyOptionsRequired());
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
View menuItemView = findViewById(item.getItemId());
PopupMenu popup = new PopupMenu(this, menuItemView);
popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
popup.show();
popup.setOnMenuItemClickListener(
popupMenuItem -> {
if (popupMenuItem.getItemId() == R.id.privacy_settings) {
// Handle changes to user consent.
googleMobileAdsConsentManager.showPrivacyOptionsForm(
this,
formError -> {
if (formError != null) {
Toast.makeText(this, formError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
return true;
}
return false;
});
return super.onOptionsItemSelected(item);
}

/** Called when leaving the activity */
@Override
public void onPause() {
if (adView != null) {
adView.pause();
}
super.onPause();
}

/** Called when leaving the activity */
@Override
public void onPause() {
if (adView != null) {
adView.pause();
}
super.onPause();
/** Called when returning to the activity */
@Override
public void onResume() {
super.onResume();
if (adView != null) {
adView.resume();
}
}

/** Called when returning to the activity */
@Override
public void onResume() {
super.onResume();
if (adView != null) {
adView.resume();
}
/** Called before the activity is destroyed */
@Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}

/** Called before the activity is destroyed */
@Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
private void initializeMobileAdsSdk() {
if (isMobileAdsInitializeCalled.getAndSet(true)) {
return;
}

// Initialize the Mobile Ads SDK.
MobileAds.initialize(
this,
new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus status) {}
});

// Create an ad request.
AdManagerAdRequest adRequest = new AdManagerAdRequest.Builder().build();
// Start loading the ad in the background.
adView.loadAd(adRequest);
}
}
10 changes: 10 additions & 0 deletions java/admanager/BannerExample/app/src/main/res/menu/action_menu.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_more"
android:icon="@android:drawable/ic_menu_preferences"
android:title="@string/more_menu"
app:showAsAction="always"
android:visible="false"/>
</menu>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/privacy_settings"
android:title="@string/privacy_settings" />
</menu>
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

<string name="app_name">BannerExample</string>
<string name="hello_world">Hello world!</string>
<string name="more_menu" translatable="false">More</string>
<string name="privacy_settings" translatable="false">Privacy Settings</string>

<!-- This is an ad unit ID for a test ad. Replace with your own banner ad unit id. -->
<string name="ad_unit_id">/6499/example/banner</string>
Expand Down
1 change: 1 addition & 0 deletions kotlin/admanager/BannerExample/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,6 @@ dependencies {
implementation "androidx.multidex:multidex:2.0.1"
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.gms:play-services-ads:22.2.0'
implementation 'com.google.android.ump:user-messaging-platform:2.1.0'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
Loading

0 comments on commit 6c32363

Please sign in to comment.