Created
November 26, 2022 10:02
-
-
Save yccheok/57b29af01330834d6767c44d832fc444 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Fragment { | |
private void displayAdMob() { | |
initializeMobileAdsAsyncIfPossible(() -> { | |
... | |
adView.loadAd(adRequest); | |
}); | |
} | |
} | |
public class Utils { | |
// volatile keyword is required : https://en.wikipedia.org/wiki/Double-checked_locking | |
// http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html | |
private static volatile boolean initializeMobileAds = false; | |
private static final Object monitor = new Object(); | |
public static void initializeMobileAdsAsyncIfPossible(Runnable runnable) { | |
if (!initializeMobileAds) { | |
// getCommonExecutor is a single thread executor. | |
getCommonExecutor().execute(() -> { | |
synchronized (monitor) { | |
if (!initializeMobileAds) { | |
// https://stackoverflow.com/questions/58084706/should-we-first-call-mobileads-setrequestconfiguration-or-mobileads-initialize | |
RequestConfiguration conf = new RequestConfiguration.Builder() | |
.setMaxAdContentRating( | |
MAX_AD_CONTENT_RATING_T) | |
.build(); | |
MobileAds.setRequestConfiguration(conf); | |
MobileAds.initialize(WeNoteApplication.instance()); | |
initializeMobileAds = true; | |
} | |
} | |
if (runnable != null) { | |
Assert(initializeMobileAds); | |
runInUiThread(runnable); | |
} | |
}); // getCommonExecutor().execute | |
} else { | |
if (runnable != null) { | |
Assert(initializeMobileAds); | |
runnable.run(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment