Skip to content

Instantly share code, notes, and snippets.

@thrashedbrain
Created January 8, 2021 06:17
Show Gist options
  • Save thrashedbrain/c1473d9793b81e8fd664f81002952c9d to your computer and use it in GitHub Desktop.
Save thrashedbrain/c1473d9793b81e8fd664f81002952c9d to your computer and use it in GitHub Desktop.
public class AdViewHelper {
private static AdViewHelper Instance;
private Context context;
ConsentForm consentForm;
AdView adView;
public static AdViewHelper getInstance(Context context, AdView adView){
if (Instance == null){
Instance = new AdHelper(context, adView);
}
return Instance;
}
private AdViewHelper(final Context context, AdView adView){
this.context = context;
this.adView = adView;
MobileAds.initialize(context);
ConsentInformation consentInformation = ConsentInformation.getInstance(context);
String[] publisherId = {context.getResources().getString(R.string.admob_pub_id)};
consentInformation.requestConsentInfoUpdate(publisherId, new ConsentInfoUpdateListener() {
@Override
public void onConsentInfoUpdated(ConsentStatus consentStatus) {
if (ConsentInformation.getInstance(context).isRequestLocationInEeaOrUnknown()){
switch (consentStatus){
case UNKNOWN:
showForm();
break;
case PERSONALIZED:
initAds(true);
break;
case NON_PERSONALIZED:
initAds(false);
break;
}
}
}
@Override
public void onFailedToUpdateConsentInfo(String reason) {
}
});
}
private void initAds(boolean personalized){
AdRequest adRequest;
if (personalized){
adRequest = new AdRequest.Builder().build();
}
else {
Bundle extras = new Bundle();
extras.putString("npa", "1");
adRequest = new AdRequest.Builder()
.addNetworkExtrasBundle(AdMobAdapter.class, extras)
.build();
}
adView.loadAd(adRequest);
}
private void showForm(){
URL privacyUrl = null;
try {
privacyUrl = new URL(context.getString(R.string.privacy_url));
} catch (MalformedURLException e) {
e.printStackTrace();
}
consentForm = new ConsentForm.Builder(context, privacyUrl)
.withListener(new ConsentFormListener() {
@Override
public void onConsentFormLoaded() {
// Consent form loaded successfully.
consentForm.show();
}
@Override
public void onConsentFormOpened() {
// Consent form was displayed.
}
@Override
public void onConsentFormClosed(ConsentStatus consentStatus, Boolean userPrefersAdFree) {
// Consent form was closed.
if (consentStatus.equals(ConsentStatus.PERSONALIZED))
initAds(true);
else
initAds(false);
}
@Override
public void onConsentFormError(String errorDescription) {
// Consent form error. This usually happens if the user is not in the EU.
}
})
.withPersonalizedAdsOption()
.withNonPersonalizedAdsOption()
.build();
consentForm.load();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment