下面列出了怎么用com.google.android.gms.ads.doubleclick.PublisherAdRequest的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Create {@link PublisherAdView} and add to container
*
* @param context - android context
* @param container - parent view for add ad view
* @return true if ads has been added
*/
public static boolean addBannerAds(Context context, @Nullable ViewGroup container) {
if (isPremiumUser(context)) {
if (container != null) {
container.setVisibility(View.GONE);
}
return false;
} else {
if (container == null) return false;
container.setVisibility(View.VISIBLE);
PublisherAdView publisherAdView = new PublisherAdView(context);
publisherAdView.setAdSizes(AdSize.SMART_BANNER, AdSize.FLUID);
publisherAdView.setAdUnitId(AdConstants.AdUnitId.AD_UNIT_ID_NATIVE_MAIN_320_50);
PublisherAdRequest.Builder builder = new PublisherAdRequest.Builder();
if (BuildConfig.DEBUG) builder.addTestDevice(TEST_DEVICE_ID);
publisherAdView.loadAd(builder.build());
container.removeAllViews();
container.addView(publisherAdView);
}
return false;
}
@Nullable
public static PublisherAdView addBannerAds(Context context, @Nullable ViewGroup container, AdSize... adSizes) {
if (isPremiumUser(context)) {
if (container != null) {
container.setVisibility(View.GONE);
}
return null;
} else {
if (container == null) return null;
container.setVisibility(View.VISIBLE);
PublisherAdView publisherAdView = new PublisherAdView(context);
publisherAdView.setAdSizes(adSizes);
publisherAdView.setAdUnitId(AdConstants.AdUnitId.AD_UNIT_ID_NATIVE_MAIN_320_50);
PublisherAdRequest.Builder builder = new PublisherAdRequest.Builder();
if (BuildConfig.DEBUG) builder.addTestDevice(TEST_DEVICE_ID);
publisherAdView.loadAd(builder.build());
container.removeAllViews();
container.addView(publisherAdView);
return publisherAdView;
}
}
@Test
public void testApplyBidsToDFOAdObject() throws Exception {
PublisherAdRequest.Builder builder = new PublisherAdRequest.Builder();
builder.addCustomTargeting("Key", "Value");
HashMap<String, String> bids = new HashMap<>();
bids.put("hb_pb", "0.50");
bids.put("hb_cache_id", "123456");
PublisherAdRequest request = builder.build();
Util.apply(bids, request);
assertEquals(3, request.getCustomTargeting().size());
assertTrue(request.getCustomTargeting().containsKey("Key"));
assertEquals("Value", request.getCustomTargeting().get("Key"));
assertTrue(request.getCustomTargeting().containsKey("hb_pb"));
assertEquals("0.50", request.getCustomTargeting().get("hb_pb"));
assertTrue(request.getCustomTargeting().containsKey("hb_cache_id"));
assertEquals("123456", request.getCustomTargeting().get("hb_cache_id"));
Util.apply(null, request);
assertEquals(1, request.getCustomTargeting().size());
assertTrue(request.getCustomTargeting().containsKey("Key"));
assertEquals("Value", request.getCustomTargeting().get("Key"));
}
@Test
public void testBaseConditions() throws Exception {
PublisherAdRequest.Builder builder = new PublisherAdRequest.Builder();
PublisherAdRequest request = builder.build();
DemandFetcher demandFetcher = new DemandFetcher(request);
demandFetcher.setPeriodMillis(0);
HashSet<AdSize> sizes = new HashSet<>();
sizes.add(new AdSize(300, 250));
RequestParams requestParams = new RequestParams("12345", AdType.BANNER, sizes);
demandFetcher.setRequestParams(requestParams);
assertEquals(DemandFetcher.STATE.STOPPED, FieldUtils.readField(demandFetcher, "state", true));
demandFetcher.start();
assertEquals(DemandFetcher.STATE.RUNNING, FieldUtils.readField(demandFetcher, "state", true));
ShadowLooper fetcherLooper = Shadows.shadowOf(demandFetcher.getHandler().getLooper());
fetcherLooper.runOneTask();
Robolectric.flushBackgroundThreadScheduler();
Robolectric.flushForegroundThreadScheduler();
demandFetcher.destroy();
assertEquals(DemandFetcher.STATE.DESTROYED, FieldUtils.readField(demandFetcher, "state", true));
}
@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);
// Create an ad request. Check logcat output for the hashed device ID to
// get test ads on a physical device. e.g.
// "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device."
PublisherAdRequest adRequest = new PublisherAdRequest.Builder().build();
// Start loading the ad in the background.
adView.loadAd(adRequest);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
noExclusionsAdView =
getView().findViewById(R.id.no_exclusions_av);
dogsExcludedAdView =
getView().findViewById(R.id.exclusions_av_dogsexcluded);
catsExcludedAdView =
getView().findViewById(R.id.exclusions_av_catsexcluded);
PublisherAdRequest noExclusionsRequest = new PublisherAdRequest.Builder().build();
PublisherAdRequest dogsExcludedRequest = new PublisherAdRequest.Builder()
.addCategoryExclusion(getString(R.string.categoryexclusion_dogscategoryname))
.build();
PublisherAdRequest catsExcludedRequest = new PublisherAdRequest.Builder()
.addCategoryExclusion(getString(R.string.categoryexclusion_catscategoryname))
.build();
noExclusionsAdView.loadAd(noExclusionsRequest);
dogsExcludedAdView.loadAd(dogsExcludedRequest);
catsExcludedAdView.loadAd(catsExcludedRequest);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
usernameEditText = getView().findViewById(R.id.ppid_et_username);
loadAdButton = getView().findViewById(R.id.ppid_btn_loadad);
publisherAdView = getView().findViewById(R.id.ppid_pav_main);
loadAdButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String username = usernameEditText.getText().toString();
if (username.length() == 0) {
Toast.makeText(DFPPPIDFragment.this.getActivity(),
"The username cannot be empty", Toast.LENGTH_SHORT).show();
} else {
String ppid = generatePPID(username);
PublisherAdRequest request = new PublisherAdRequest.Builder()
.setPublisherProvidedId(ppid)
.build();
publisherAdView.loadAd(request);
}
}
});
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
sportsSpinner = getView().findViewById(R.id.customtargeting_spn_sport);
loadButton = getView().findViewById(R.id.customtargeting_btn_loadad);
adView = getView().findViewById(R.id.customtargeting_av_main);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getView().getContext(),
R.array.customtargeting_sports, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sportsSpinner.setAdapter(adapter);
loadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PublisherAdRequest adRequest = new PublisherAdRequest.Builder()
.addCustomTargeting(getString(R.string.customtargeting_key),
(String) sportsSpinner.getSelectedItem())
.build();
adView.loadAd(adRequest);
}
});
}
@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());
// Create an ad request.
PublisherAdRequest adRequest = new PublisherAdRequest.Builder().build();
// Start loading the ad in the background.
adView.loadAd(adRequest);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
noExclusionsAdView =
getView().findViewById(R.id.no_exclusions_av);
dogsExcludedAdView =
getView().findViewById(R.id.exclusions_av_dogsexcluded);
catsExcludedAdView =
getView().findViewById(R.id.exclusions_av_catsexcluded);
PublisherAdRequest noExclusionsRequest = new PublisherAdRequest.Builder().build();
PublisherAdRequest dogsExcludedRequest = new PublisherAdRequest.Builder()
.addCategoryExclusion(getString(R.string.categoryexclusion_dogscategoryname))
.build();
PublisherAdRequest catsExcludedRequest = new PublisherAdRequest.Builder()
.addCategoryExclusion(getString(R.string.categoryexclusion_catscategoryname))
.build();
noExclusionsAdView.loadAd(noExclusionsRequest);
dogsExcludedAdView.loadAd(dogsExcludedRequest);
catsExcludedAdView.loadAd(catsExcludedRequest);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
usernameEditText = getView().findViewById(R.id.ppid_et_username);
loadAdButton = getView().findViewById(R.id.ppid_btn_loadad);
publisherAdView = getView().findViewById(R.id.ppid_pav_main);
loadAdButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String username = usernameEditText.getText().toString();
if (username.length() == 0) {
Toast.makeText(DFPPPIDFragment.this.getActivity(),
"The username cannot be empty", Toast.LENGTH_SHORT).show();
} else {
String ppid = generatePPID(username);
PublisherAdRequest request = new PublisherAdRequest.Builder()
.setPublisherProvidedId(ppid)
.build();
publisherAdView.loadAd(request);
}
}
});
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
sportsSpinner = getView().findViewById(R.id.customtargeting_spn_sport);
loadButton = getView().findViewById(R.id.customtargeting_btn_loadad);
adView = getView().findViewById(R.id.customtargeting_av_main);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getView().getContext(),
R.array.customtargeting_sports, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sportsSpinner.setAdapter(adapter);
loadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PublisherAdRequest adRequest = new PublisherAdRequest.Builder()
.addCustomTargeting(getString(R.string.customtargeting_key),
(String) sportsSpinner.getSelectedItem())
.build();
adView.loadAd(adRequest);
}
});
}
private PublisherAdRequest buildRequest(TargetingParameters targetingParameters) {
PublisherAdRequest.Builder builder = new PublisherAdRequest.Builder();
Bundle bundle = new Bundle();
if (targetingParameters.getAge() != null) {
bundle.putString("Age", targetingParameters.getAge());
}
if (targetingParameters.getLocation() != null) {
builder.setLocation(targetingParameters.getLocation());
}
for (Pair<String, String> p : targetingParameters.getCustomKeywords()) {
if (p.first.equals("content_url")) {
if (!StringUtil.isEmpty(p.second)) {
builder.setContentUrl(p.second);
}
} else {
bundle.putString(p.first, p.second);
}
}
//Since AdMobExtras is deprecated so we need to use below method
builder.addNetworkExtrasBundle(com.google.ads.mediation.admob.AdMobAdapter.class, bundle);
return builder.build();
}
private void loadAMBanner() {
FrameLayout adFrame = findViewById(R.id.adFrame);
adFrame.removeAllViews();
adFrame.addView(amBanner);
amBanner.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
super.onAdLoaded();
AdViewUtils.findPrebidCreativeSize(amBanner, new AdViewUtils.PbFindSizeListener() {
@Override
public void success(int width, int height) {
amBanner.setAdSizes(new AdSize(width, height));
}
@Override
public void failure(@NonNull PbFindSizeError error) {
Log.d("MyTag", "error: " + error);
}
});
}
});
final PublisherAdRequest.Builder builder = new PublisherAdRequest.Builder();
final PublisherAdRequest request = builder.build();
//region PrebidMobile Mobile API 1.0 usage
int millis = getIntent().getIntExtra(Constants.AUTO_REFRESH_NAME, 0);
adUnit.setAutoRefreshPeriodMillis(millis);
adUnit.fetchDemand(request, new OnCompleteListener() {
@Override
public void onComplete(ResultCode resultCode) {
DemoActivity.this.resultCode = resultCode;
amBanner.loadAd(request);
refreshCount++;
}
});
}
private void loadAMInterstitial() {
int millis = getIntent().getIntExtra(Constants.AUTO_REFRESH_NAME, 0);
adUnit.setAutoRefreshPeriodMillis(millis);
PublisherAdRequest.Builder builder = new PublisherAdRequest.Builder();
request = builder.build();
adUnit.fetchDemand(request, new OnCompleteListener() {
@Override
public void onComplete(ResultCode resultCode) {
DemoActivity.this.resultCode = resultCode;
amInterstitial.loadAd(request);
refreshCount++;
}
});
}
@Test
public void testSupportedAdObject() throws Exception {
MoPubView testView = new MoPubView(activity);
assertTrue(Util.supportedAdObject(testView));
assertFalse(Util.supportedAdObject(null));
MoPubInterstitial interstitial = new MoPubInterstitial(activity, "");
assertTrue(Util.supportedAdObject(interstitial));
PublisherAdRequest request = new PublisherAdRequest.Builder().build();
assertTrue(Util.supportedAdObject(request));
Object object = new Object();
assertFalse(Util.supportedAdObject(object));
}
@Test
public void testSupportMultipleSizesForDFPBanner() throws Exception {
PrebidMobile.setPrebidServerAccountId("123456");
BannerAdUnit adUnit = new BannerAdUnit("123456", 320, 50);
adUnit.addAdditionalSize(300, 250);
OnCompleteListener mockListener = mock(OnCompleteListener.class);
PublisherAdRequest.Builder builder = new PublisherAdRequest.Builder();
adUnit.fetchDemand(builder.build(), mockListener);
verify(mockListener, never()).onComplete(ResultCode.INVALID_SIZE);
}
@Test
public void testSingleRequestNoBidsResponse() throws Exception {
HttpUrl httpUrl = server.url("/");
PrebidMobile.setApplicationContext(activity);
Host.CUSTOM.setHostUrl(httpUrl.toString());
PrebidMobile.setPrebidServerHost(Host.CUSTOM);
server.enqueue(new MockResponse().setResponseCode(200).setBody(MockPrebidServerResponses.noBid()));
PublisherAdRequest.Builder builder = new PublisherAdRequest.Builder();
PublisherAdRequest request = builder.build();
DemandFetcher demandFetcher = new DemandFetcher(request);
PrebidMobile.setTimeoutMillis(Integer.MAX_VALUE);
demandFetcher.setPeriodMillis(0);
HashSet<AdSize> sizes = new HashSet<>();
sizes.add(new AdSize(300, 250));
RequestParams requestParams = new RequestParams("12345", AdType.BANNER, sizes);
demandFetcher.setRequestParams(requestParams);
OnCompleteListener mockListener = mock(OnCompleteListener.class);
demandFetcher.setListener(mockListener);
assertEquals(DemandFetcher.STATE.STOPPED, FieldUtils.readField(demandFetcher, "state", true));
demandFetcher.start();
assertEquals(DemandFetcher.STATE.RUNNING, FieldUtils.readField(demandFetcher, "state", true));
ShadowLooper fetcherLooper = Shadows.shadowOf(demandFetcher.getHandler().getLooper());
fetcherLooper.runOneTask();
ShadowLooper demandLooper = Shadows.shadowOf(demandFetcher.getDemandHandler().getLooper());
demandLooper.runOneTask();
Robolectric.flushBackgroundThreadScheduler();
Robolectric.flushForegroundThreadScheduler();
verify(mockListener).onComplete(ResultCode.NO_BIDS);
assertEquals(DemandFetcher.STATE.DESTROYED, FieldUtils.readField(demandFetcher, "state", true));
}
@Test
public void testDestroyAutoRefresh() throws Exception {
HttpUrl httpUrl = server.url("/");
PrebidMobile.setApplicationContext(activity);
Host.CUSTOM.setHostUrl(httpUrl.toString());
PrebidMobile.setPrebidServerHost(Host.CUSTOM);
server.enqueue(new MockResponse().setResponseCode(200).setBody(MockPrebidServerResponses.noBid()));
server.enqueue(new MockResponse().setResponseCode(200).setBody(MockPrebidServerResponses.noBid()));
server.enqueue(new MockResponse().setResponseCode(200).setBody(MockPrebidServerResponses.noBid()));
PublisherAdRequest.Builder builder = new PublisherAdRequest.Builder();
PublisherAdRequest request = builder.build();
DemandFetcher demandFetcher = new DemandFetcher(request);
PrebidMobile.setTimeoutMillis(Integer.MAX_VALUE);
demandFetcher.setPeriodMillis(30);
HashSet<AdSize> sizes = new HashSet<>();
sizes.add(new AdSize(300, 250));
RequestParams requestParams = new RequestParams("12345", AdType.BANNER, sizes);
demandFetcher.setRequestParams(requestParams);
OnCompleteListener mockListener = mock(OnCompleteListener.class);
demandFetcher.setListener(mockListener);
assertEquals(DemandFetcher.STATE.STOPPED, FieldUtils.readField(demandFetcher, "state", true));
demandFetcher.start();
assertEquals(DemandFetcher.STATE.RUNNING, FieldUtils.readField(demandFetcher, "state", true));
ShadowLooper fetcherLooper = Shadows.shadowOf(demandFetcher.getHandler().getLooper());
fetcherLooper.runOneTask();
ShadowLooper demandLooper = Shadows.shadowOf(demandFetcher.getDemandHandler().getLooper());
demandLooper.runOneTask();
Robolectric.flushBackgroundThreadScheduler();
Robolectric.flushForegroundThreadScheduler();
assertEquals(DemandFetcher.STATE.RUNNING, FieldUtils.readField(demandFetcher, "state", true));
demandFetcher.destroy();
assertTrue(!Robolectric.getForegroundThreadScheduler().areAnyRunnable());
assertTrue(!Robolectric.getBackgroundThreadScheduler().areAnyRunnable());
assertEquals(DemandFetcher.STATE.DESTROYED, FieldUtils.readField(demandFetcher, "state", true));
verify(mockListener, Mockito.times(1)).onComplete(ResultCode.NO_BIDS);
}
private void startGame() {
// Request a new ad if one isn't already loaded, hide the button, and kick off the timer.
if (!adIsLoading && !interstitialAd.isLoaded()) {
adIsLoading = true;
PublisherAdRequest adRequest = new PublisherAdRequest.Builder().build();
interstitialAd.loadAd(adRequest);
}
retryButton.setVisibility(View.INVISIBLE);
resumeGame(GAME_LENGTH_MILLISECONDS);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
adView = getView().findViewById(R.id.appevents_av_main);
adView.setAppEventListener(new AppEventListener() {
@Override
public void onAppEvent(String name, String data) {
// The DFP ad that this fragment loads contains JavaScript code that sends App
// Events to the host application. This AppEventListener receives those events,
// and sets the background of the fragment to match the data that comes in.
// The ad will send "red" when it loads, "blue" five seconds later, and "green"
// if the user taps the ad.
// This is just a demonstration, of course. Your apps can do much more interesting
// things with App Events.
if (name.equals("color")) {
switch (data) {
case "blue":
rootView.setBackgroundColor(Color.rgb(0xD0, 0xD0, 0xFF));
break;
case "red":
rootView.setBackgroundColor(Color.rgb(0xFF, 0xD0, 0xD0));
break;
case "green":
rootView.setBackgroundColor(Color.rgb(0xD0, 0xFF, 0xD0));
break;
}
}
}
});
PublisherAdRequest adRequest = new PublisherAdRequest.Builder().build();
adView.loadAd(adRequest);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// The size for this PublisherAdView is defined in the XML layout as AdSize.FLUID. It could
// also be set here by calling publisherAdView.setAdSizes(AdSize.FLUID).
//
// An ad with fluid size will automatically stretch or shrink to fit the height of its
// content, which can help layout designers cut down on excess whitespace.
publisherAdView = getView().findViewById(R.id.fluid_av_main);
PublisherAdRequest publisherAdRequest = new PublisherAdRequest.Builder().build();
publisherAdView.loadAd(publisherAdRequest);
changeAdViewWidthButton = getView().findViewById(R.id.fluid_btn_change_width);
changeAdViewWidthButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int newWidth = adViewWidths[currentIndex % adViewWidths.length];
currentIndex += 1;
// Change the PublisherAdView's width.
ViewGroup.LayoutParams layoutParams = publisherAdView.getLayoutParams();
final float scale = getResources().getDisplayMetrics().density;
layoutParams.width = (int) (newWidth * scale + 0.5f);
publisherAdView.setLayoutParams(layoutParams);
// Update the TextView with the new width.
currentWidthTextView = getView().findViewById(R.id.fluid_tv_current_width);
currentWidthTextView.setText(
String.format(Locale.getDefault(), "%d dp", newWidth));
}
});
}
public void loadBanner() {
ArrayList<AdSize> adSizes = new ArrayList<AdSize>();
if (this.adSize != null) {
adSizes.add(this.adSize);
}
if (this.validAdSizes != null) {
for (int i = 0; i < this.validAdSizes.length; i++) {
adSizes.add(this.validAdSizes[i]);
}
}
if (adSizes.size() == 0) {
adSizes.add(AdSize.BANNER);
}
AdSize[] adSizesArray = adSizes.toArray(new AdSize[adSizes.size()]);
this.adView.setAdSizes(adSizesArray);
PublisherAdRequest.Builder adRequestBuilder = new PublisherAdRequest.Builder();
if (testDevices != null) {
for (int i = 0; i < testDevices.length; i++) {
String testDevice = testDevices[i];
if (testDevice == "SIMULATOR") {
testDevice = PublisherAdRequest.DEVICE_ID_EMULATOR;
}
adRequestBuilder.addTestDevice(testDevice);
}
}
PublisherAdRequest adRequest = adRequestBuilder.build();
this.adView.loadAd(adRequest);
}
private void loadBanner(AdSize adSize) {
// Create an ad request.
adView = new PublisherAdView(this);
adView.setAdUnitId(BACKFILL_IU);
adView.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light));
adContainerView.removeAllViews();
adContainerView.addView(adView);
adView.setAdSizes(adSize);
PublisherAdRequest adRequest = new PublisherAdRequest.Builder().build();
// Start loading the ad in the background.
adView.loadAd(adRequest);
}
private void startGame() {
// Request a new ad if one isn't already loaded, hide the button, and kick off the timer.
if (!adIsLoading && !interstitialAd.isLoaded()) {
adIsLoading = true;
PublisherAdRequest adRequest = new PublisherAdRequest.Builder().build();
interstitialAd.loadAd(adRequest);
}
retryButton.setVisibility(View.INVISIBLE);
resumeGame(GAME_LENGTH_MILLISECONDS);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
adView = getView().findViewById(R.id.appevents_av_main);
adView.setAppEventListener(new AppEventListener() {
@Override
public void onAppEvent(String name, String data) {
// The DFP ad that this fragment loads contains JavaScript code that sends App
// Events to the host application. This AppEventListener receives those events,
// and sets the background of the fragment to match the data that comes in.
// The ad will send "red" when it loads, "blue" five seconds later, and "green"
// if the user taps the ad.
// This is just a demonstration, of course. Your apps can do much more interesting
// things with App Events.
if (name.equals("color")) {
switch (data) {
case "blue":
rootView.setBackgroundColor(Color.rgb(0xD0, 0xD0, 0xFF));
break;
case "red":
rootView.setBackgroundColor(Color.rgb(0xFF, 0xD0, 0xD0));
break;
case "green":
rootView.setBackgroundColor(Color.rgb(0xD0, 0xFF, 0xD0));
break;
}
}
}
});
PublisherAdRequest adRequest = new PublisherAdRequest.Builder().build();
adView.loadAd(adRequest);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// The size for this PublisherAdView is defined in the XML layout as AdSize.FLUID. It could
// also be set here by calling publisherAdView.setAdSizes(AdSize.FLUID).
//
// An ad with fluid size will automatically stretch or shrink to fit the height of its
// content, which can help layout designers cut down on excess whitespace.
publisherAdView = getView().findViewById(R.id.fluid_av_main);
PublisherAdRequest publisherAdRequest = new PublisherAdRequest.Builder().build();
publisherAdView.loadAd(publisherAdRequest);
changeAdViewWidthButton = getView().findViewById(R.id.fluid_btn_change_width);
changeAdViewWidthButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int newWidth = adViewWidths[currentIndex % adViewWidths.length];
currentIndex += 1;
// Change the PublisherAdView's width.
ViewGroup.LayoutParams layoutParams = publisherAdView.getLayoutParams();
final float scale = getResources().getDisplayMetrics().density;
layoutParams.width = (int) (newWidth * scale + 0.5f);
publisherAdView.setLayoutParams(layoutParams);
// Update the TextView with the new width.
currentWidthTextView = getView().findViewById(R.id.fluid_tv_current_width);
currentWidthTextView.setText(
String.format(Locale.getDefault(), "%d dp", newWidth));
}
});
}
void createDFPNative() {
FrameLayout adFrame = (FrameLayout) findViewById(R.id.adFrame);
adFrame.removeAllViews();
final PublisherAdView nativeAdView = new PublisherAdView(this);
nativeAdView.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
super.onAdLoaded();
LogUtil.d("ad loaded");
}
});
nativeAdView.setAdUnitId(Constants.DFP_IN_BANNER_NATIVE_ADUNIT_ID_APPNEXUS);
nativeAdView.setAdSizes(AdSize.FLUID);
adFrame.addView(nativeAdView);
final PublisherAdRequest.Builder builder = new PublisherAdRequest.Builder();
request = builder.build();
NativeAdUnit nativeAdUnit = (NativeAdUnit) adUnit;
nativeAdUnit.setContextType(NativeAdUnit.CONTEXT_TYPE.SOCIAL_CENTRIC);
nativeAdUnit.setPlacementType(NativeAdUnit.PLACEMENTTYPE.CONTENT_FEED);
nativeAdUnit.setContextSubType(NativeAdUnit.CONTEXTSUBTYPE.GENERAL_SOCIAL);
ArrayList<NativeEventTracker.EVENT_TRACKING_METHOD> methods = new ArrayList<>();
methods.add(NativeEventTracker.EVENT_TRACKING_METHOD.IMAGE);
try {
NativeEventTracker tracker = new NativeEventTracker(NativeEventTracker.EVENT_TYPE.IMPRESSION, methods);
nativeAdUnit.addEventTracker(tracker);
} catch (Exception e) {
e.printStackTrace();
}
NativeTitleAsset title = new NativeTitleAsset();
title.setLength(90);
title.setRequired(true);
nativeAdUnit.addAsset(title);
NativeImageAsset icon = new NativeImageAsset();
icon.setImageType(NativeImageAsset.IMAGE_TYPE.ICON);
icon.setWMin(20);
icon.setHMin(20);
icon.setRequired(true);
nativeAdUnit.addAsset(icon);
NativeImageAsset image = new NativeImageAsset();
image.setImageType(NativeImageAsset.IMAGE_TYPE.MAIN);
image.setHMin(200);
image.setWMin(200);
image.setRequired(true);
nativeAdUnit.addAsset(image);
NativeDataAsset data = new NativeDataAsset();
data.setLen(90);
data.setDataType(NativeDataAsset.DATA_TYPE.SPONSORED);
data.setRequired(true);
nativeAdUnit.addAsset(data);
NativeDataAsset body = new NativeDataAsset();
body.setRequired(true);
body.setDataType(NativeDataAsset.DATA_TYPE.DESC);
nativeAdUnit.addAsset(body);
NativeDataAsset cta = new NativeDataAsset();
cta.setRequired(true);
cta.setDataType(NativeDataAsset.DATA_TYPE.CTATEXT);
nativeAdUnit.addAsset(cta);
int millis = getIntent().getIntExtra(Constants.AUTO_REFRESH_NAME, 0);
nativeAdUnit.setAutoRefreshPeriodMillis(millis);
nativeAdUnit.fetchDemand(request, new OnCompleteListener() {
@Override
public void onComplete(ResultCode resultCode) {
DemoActivity.this.resultCode = resultCode;
nativeAdView.loadAd(request);
DemoActivity.this.request = request;
refreshCount++;
}
});
}
@Test
public void testGetClassFromString() throws Exception {
assertEquals(MoPubView.class, Util.getClassFromString(Util.MOPUB_BANNER_VIEW_CLASS));
assertEquals(MoPubInterstitial.class, Util.getClassFromString(Util.MOPUB_INTERSTITIAL_CLASS));
assertEquals(PublisherAdRequest.class, Util.getClassFromString(Util.DFP_AD_REQUEST_CLASS));
}
@Test
public void testSuccessForDFP() throws Exception {
HttpUrl httpUrl = server.url("/");
Host.CUSTOM.setHostUrl(httpUrl.toString());
PrebidMobile.setPrebidServerHost(Host.CUSTOM);
PrebidMobile.setApplicationContext(activity.getApplicationContext());
PrebidMobile.setPrebidServerAccountId("123456");
server.enqueue(new MockResponse().setResponseCode(200).setBody(MockPrebidServerResponses.oneBidFromAppNexus()));
BannerAdUnit adUnit = new BannerAdUnit("123456", 300, 250);
PublisherAdRequest testRequest = new PublisherAdRequest.Builder().build();
OnCompleteListener mockListener = mock(OnCompleteListener.class);
adUnit.fetchDemand(testRequest, mockListener);
DemandFetcher fetcher = (DemandFetcher) FieldUtils.readField(adUnit, "fetcher", true);
PrebidMobile.setTimeoutMillis(Integer.MAX_VALUE);
ShadowLooper fetcherLooper = shadowOf(fetcher.getHandler().getLooper());
fetcherLooper.runOneTask();
ShadowLooper demandLooper = shadowOf(fetcher.getDemandHandler().getLooper());
demandLooper.runOneTask();
Robolectric.flushBackgroundThreadScheduler();
Robolectric.flushForegroundThreadScheduler();
verify(mockListener).onComplete(ResultCode.SUCCESS);
Bundle bundle = testRequest.getCustomTargeting();
assertEquals(10, bundle.size());
assertTrue(bundle.containsKey("hb_pb"));
assertEquals("0.50", bundle.get("hb_pb"));
assertTrue(bundle.containsKey("hb_bidder"));
assertEquals("appnexus", bundle.get("hb_bidder"));
assertTrue(bundle.containsKey("hb_bidder_appnexus"));
assertEquals("appnexus", bundle.get("hb_bidder_appnexus"));
assertTrue(bundle.containsKey("hb_cache_id"));
assertEquals("df4aba04-5e69-44b8-8608-058ab21600b8", bundle.get("hb_cache_id"));
assertTrue(bundle.containsKey("hb_cache_id_appnexus"));
assertEquals("df4aba04-5e69-44b8-8608-058ab21600b8", bundle.get("hb_cache_id_appnexus"));
assertTrue(bundle.containsKey("hb_env"));
assertEquals("mobile-app", bundle.get("hb_env"));
assertTrue(bundle.containsKey("hb_env_appnexus"));
assertEquals("mobile-app", bundle.get("hb_env_appnexus"));
assertTrue(bundle.containsKey("hb_pb_appnexus"));
assertEquals("0.50", bundle.get("hb_pb_appnexus"));
assertTrue(bundle.containsKey("hb_size"));
assertEquals("300x250", bundle.get("hb_size"));
assertTrue(bundle.containsKey("hb_size_appnexus"));
assertEquals("300x250", bundle.get("hb_size_appnexus"));
}