com.google.android.gms.ads.doubleclick.PublisherAdRequest Java Examples

The following examples show how to use com.google.android.gms.ads.doubleclick.PublisherAdRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AdsManager.java    From text_converter with GNU General Public License v3.0 6 votes vote down vote up
@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;
    }
}
 
Example #2
Source File: GooglePlayDFPInterstitial.java    From mobile-sdk-android with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #3
Source File: DFPCustomTargetingFragment.java    From googleads-mobile-android-examples with Apache License 2.0 6 votes vote down vote up
@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);
        }
    });
}
 
Example #4
Source File: DFPPPIDFragment.java    From googleads-mobile-android-examples with Apache License 2.0 6 votes vote down vote up
@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);
            }
        }
    });
}
 
Example #5
Source File: DFPCategoryExclusionFragment.java    From googleads-mobile-android-examples with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #6
Source File: MyActivity.java    From googleads-mobile-android-examples with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #7
Source File: DFPCustomTargetingFragment.java    From android-ads with Apache License 2.0 6 votes vote down vote up
@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);
        }
    });
}
 
Example #8
Source File: DFPPPIDFragment.java    From android-ads with Apache License 2.0 6 votes vote down vote up
@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);
            }
        }
    });
}
 
Example #9
Source File: DFPCategoryExclusionFragment.java    From android-ads with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #10
Source File: MyActivity.java    From android-ads with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #11
Source File: DemandFetcherTest.java    From prebid-mobile-android with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #12
Source File: UtilTest.java    From prebid-mobile-android with Apache License 2.0 6 votes vote down vote up
@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"));
}
 
Example #13
Source File: AdsManager.java    From text_converter with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #14
Source File: DFPAppEventsFragment.java    From android-ads with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #15
Source File: DemoActivity.java    From prebid-mobile-android with Apache License 2.0 5 votes vote down vote up
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++;
        }
    });
}
 
Example #16
Source File: MyActivity.java    From googleads-mobile-android-examples with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #17
Source File: MyActivity.java    From googleads-mobile-android-examples with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #18
Source File: RNPublisherBannerViewManager.java    From react-native-admob with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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);
}
 
Example #19
Source File: DemandFetcherTest.java    From prebid-mobile-android with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #20
Source File: ResultCodeTest.java    From prebid-mobile-android with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #21
Source File: DFPFluidSizeFragment.java    From android-ads with Apache License 2.0 5 votes vote down vote up
@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));
        }
    });
}
 
Example #22
Source File: DemoActivity.java    From prebid-mobile-android with Apache License 2.0 5 votes vote down vote up
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++;
        }
    });
}
 
Example #23
Source File: UtilTest.java    From prebid-mobile-android with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #24
Source File: DFPAppEventsFragment.java    From googleads-mobile-android-examples with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #25
Source File: DFPFluidSizeFragment.java    From googleads-mobile-android-examples with Apache License 2.0 5 votes vote down vote up
@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));
        }
    });
}
 
Example #26
Source File: MyActivity.java    From android-ads with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #27
Source File: DemandFetcherTest.java    From prebid-mobile-android with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #28
Source File: RNPublisherBannerViewManager.java    From react-native-admob with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void createAdView() {
    if (this.adView != null) this.adView.destroy();

    final Context context = getContext();
    this.adView = new PublisherAdView(context);
    this.adView.setAppEventListener(this);
    this.adView.setAdListener(new AdListener() {
        @Override
        public void onAdLoaded() {
            int width = adView.getAdSize().getWidthInPixels(context);
            int height = adView.getAdSize().getHeightInPixels(context);
            int left = adView.getLeft();
            int top = adView.getTop();
            adView.measure(width, height);
            adView.layout(left, top, left + width, top + height);
            sendOnSizeChangeEvent();
            sendEvent(RNPublisherBannerViewManager.EVENT_AD_LOADED, null);
        }

        @Override
        public void onAdFailedToLoad(int errorCode) {
            String errorMessage = "Unknown error";
            switch (errorCode) {
                case PublisherAdRequest.ERROR_CODE_INTERNAL_ERROR:
                    errorMessage = "Internal error, an invalid response was received from the ad server.";
                    break;
                case PublisherAdRequest.ERROR_CODE_INVALID_REQUEST:
                    errorMessage = "Invalid ad request, possibly an incorrect ad unit ID was given.";
                    break;
                case PublisherAdRequest.ERROR_CODE_NETWORK_ERROR:
                    errorMessage = "The ad request was unsuccessful due to network connectivity.";
                    break;
                case PublisherAdRequest.ERROR_CODE_NO_FILL:
                    errorMessage = "The ad request was successful, but no ad was returned due to lack of ad inventory.";
                    break;
            }
            WritableMap event = Arguments.createMap();
            WritableMap error = Arguments.createMap();
            error.putString("message", errorMessage);
            event.putMap("error", error);
            sendEvent(RNPublisherBannerViewManager.EVENT_AD_FAILED_TO_LOAD, event);
        }

        @Override
        public void onAdOpened() {
            sendEvent(RNPublisherBannerViewManager.EVENT_AD_OPENED, null);
        }

        @Override
        public void onAdClosed() {
            sendEvent(RNPublisherBannerViewManager.EVENT_AD_CLOSED, null);
        }

        @Override
        public void onAdLeftApplication() {
            sendEvent(RNPublisherBannerViewManager.EVENT_AD_LEFT_APPLICATION, null);
        }
    });
    this.addView(this.adView);
}
 
Example #29
Source File: DFPMultipleAdSizesFragment.java    From googleads-mobile-android-examples with Apache License 2.0 4 votes vote down vote up
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    loadButton = getView().findViewById(R.id.adsizes_btn_loadad);
    cb120x20 = getView().findViewById(R.id.adsizes_cb_120x20);
    cb320x50 = getView().findViewById(R.id.adsizes_cb_320x50);
    cb300x250 = getView().findViewById(R.id.adsizes_cb_300x250);
    publisherAdView = getView().findViewById(R.id.adsizes_pav_main);

    publisherAdView.setAdListener(new AdListener() {
        @Override
        public void onAdLoaded() {
            publisherAdView.setVisibility(View.VISIBLE);
        }
    });

    loadButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (!cb120x20.isChecked()
                    && !cb320x50.isChecked()
                    && !cb300x250.isChecked()) {
                Toast.makeText(DFPMultipleAdSizesFragment.this.getActivity(),
                        "At least one size is required.", Toast.LENGTH_SHORT).show();
            } else {
                List<AdSize> sizeList = new ArrayList<>();

                if (cb120x20.isChecked()) {
                    sizeList.add(new AdSize(120, 20));
                }

                if (cb320x50.isChecked()) {
                    sizeList.add(AdSize.BANNER);
                }

                if (cb300x250.isChecked()) {
                    sizeList.add(AdSize.MEDIUM_RECTANGLE);
                }

                publisherAdView.setVisibility(View.INVISIBLE);
                publisherAdView.setAdSizes(sizeList.toArray(new AdSize[sizeList.size()]));
                publisherAdView.loadAd(new PublisherAdRequest.Builder().build());
            }
        }
    });
}
 
Example #30
Source File: DemoActivity.java    From prebid-mobile-android with Apache License 2.0 4 votes vote down vote up
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++;
        }
    });
}