I'm trying to add the Google User Messaging Platform SDK to my app so that it can serve ads to EEA and UK users.
I'm following every step in the this guide. https://developers.google.com/admob/android/privacy
However, I'm getting an error "cannot find symbol variable canRequestAds" on this line of code consentInformation.canRequestAds
import com.google.android.gms.ads.MobileAds;
import com.google.android.material.tabs.TabLayout;
import com.google.android.ump.ConsentForm;
import com.google.android.ump.ConsentInformation;
import com.google.android.ump.ConsentRequestParameters;
import com.google.android.ump.UserMessagingPlatform;
import java.util.concurrent.atomic.AtomicBoolean;
public class MainActivity extends AppCompatActivity {
private ConsentInformation consentInformation;
// Use an atomic boolean to initialize the Google Mobile Ads SDK and load ads once.
private final AtomicBoolean isMobileAdsInitializeCalled = new AtomicBoolean(false);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set tag for under age of consent. false means users are not under age
// of consent.
ConsentRequestParameters params = new ConsentRequestParameters
.Builder()
.setTagForUnderAgeOfConsent(false)
.build();
consentInformation = UserMessagingPlatform.getConsentInformation(this);
consentInformation.requestConsentInfoUpdate(
this,
params,
(OnConsentInfoUpdateSuccessListener) () -> {
UserMessagingPlatform.loadAndShowConsentFormIfRequired(
this,
(OnConsentFormDismissedListener) loadAndShowError -> {
if (loadAndShowError != null) {
// Consent gathering failed.
Log.w(TAG, String.format("%s: %s",
loadAndShowError.getErrorCode(),
loadAndShowError.getMessage()));
}
// Consent has been gathered.
if (consentInformation.canRequestAds) {
initializeMobileAdsSdk();
}
}
)
},
(OnConsentInfoUpdateFailureListener) requestConsentError -> {
// Consent gathering failed.
Log.w(TAG, String.format("%s: %s",
requestConsentError.getErrorCode(),
requestConsentError.getMessage()));
});
// Check if you can initialize the Google Mobile Ads SDK in parallel
// while checking for new consent information. Consent obtained in
// the previous session can be used to request ads.
if (consentInformation.canRequestAds) {
initializeMobileAdsSdk();
}
}
private void initializeMobileAdsSdk() {
if (isMobileAdsInitializeCalled.getAndSet(true)) {
return;
}
// Initialize the Google Mobile Ads SDK.
MobileAds.initialize(this);
// TODO: Request an ad.
// InterstitialAd.load(...);
}
}
I had the same problem and decompiled ConsentInformation interface. There's an error in the code provided by Google -
canRequestAds
is not a field but a method, so you should usecanRequestAds()
instead ofcanRequestAds