Skip to content

Commit

Permalink
Added java preloading sample to APIDemo.
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 693515110
  • Loading branch information
nventimigli authored and copybara-github committed Nov 6, 2024
1 parent 696934f commit d5b16e0
Show file tree
Hide file tree
Showing 13 changed files with 474 additions and 3 deletions.
2 changes: 1 addition & 1 deletion java/advanced/APIDemo/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ android {
compileSdkVersion 34
defaultConfig {
applicationId "com.google.android.gms.example.apidemo"
minSdkVersion 21
minSdkVersion 24
multiDexEnabled true
targetSdkVersion 34
versionCode 1
Expand Down
1 change: 1 addition & 0 deletions java/advanced/APIDemo/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

<application
android:allowBackup="true"
android:networkSecurityConfig="@xml/network_security_config"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:taskAffinity=""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.RequestConfiguration;
import com.google.android.gms.example.apidemo.databinding.ActivityMainBinding;
import com.google.android.gms.example.apidemo.preloading.AdMobPreloadingAdsFragment;
import com.google.android.material.navigation.NavigationView;
import java.util.Arrays;

Expand Down Expand Up @@ -95,6 +96,9 @@ public boolean onNavigationItemSelected(MenuItem item) {
case R.id.nav_admob_custommute:
newFragment = new AdMobCustomMuteThisAdFragment();
break;
case R.id.nav_admob_preload:
newFragment = new AdMobPreloadingAdsFragment();
break;
case R.id.nav_gam_adsizes:
newFragment = new AdManagerMultipleAdSizesFragment();
break;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.android.gms.example.apidemo.preloading;

import static com.google.android.gms.example.apidemo.MainActivity.LOG_TAG;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import com.google.android.gms.ads.AdFormat;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.preload.PreloadCallback;
import com.google.android.gms.ads.preload.PreloadConfiguration;
import com.google.android.gms.example.apidemo.R;
import com.google.android.gms.example.apidemo.databinding.FragmentPreloadItemBinding;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/** Demonstrates how to preload ads. */
public class AdMobPreloadingAdsFragment extends PreloadItemFragment {

private final List<PreloadItemFragment> fragmentList = new ArrayList<>();

@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout.
FragmentPreloadItemBinding viewBinding =
FragmentPreloadItemBinding.inflate(getLayoutInflater());

// Initialize the fragments UI.
addFragmentsUI();

// Start preloading ads.
startPreload();

return viewBinding.getRoot();
}

// [START start_preload]
private void startPreload() {
// Define the number of ads that can be preloaded for each ad unit.
int bufferSize = 2;
// Define a list of PreloadConfiguration objects, specifying the ad unit ID and ad format for
// each ad unit to be preloaded.
List<PreloadConfiguration> preloadConfigs =
Arrays.asList(
new PreloadConfiguration.Builder(InterstitialFragment.AD_UNIT_ID, AdFormat.INTERSTITIAL)
.setBufferSize(bufferSize)
.build(),
new PreloadConfiguration.Builder(RewardedFragment.AD_UNIT_ID, AdFormat.REWARDED)
.setBufferSize(bufferSize)
.build(),
new PreloadConfiguration.Builder(AppOpenFragment.AD_UNIT_ID, AdFormat.APP_OPEN_AD)
.setBufferSize(bufferSize)
.build());

// Define a callback to receive preload availability events.
PreloadCallback callback =
new PreloadCallback() {
@Override
public void onAdsAvailable(@NonNull PreloadConfiguration preloadConfig) {
Log.i(LOG_TAG, "Preload ad for " + preloadConfig.getAdFormat() + " is available.");
updateUI();
}

@Override
public void onAdsExhausted(@NonNull PreloadConfiguration preloadConfig) {
Log.i(LOG_TAG, "Preload ad for " + preloadConfig.getAdFormat() + " is exhausted.");
updateUI();
}
};

// Start the preloading initialization process.
MobileAds.startPreload(this.requireContext(), preloadConfigs, callback);
}

// [END start_preload]

private void addFragmentsUI() {
addFragmentUI(new AppOpenFragment());
addFragmentUI(new InterstitialFragment());
addFragmentUI(new RewardedFragment());
}

private void addFragmentUI(PreloadItemFragment fragment) {
getParentFragmentManager().beginTransaction().add(R.id.list_formats, fragment).commit();
fragmentList.add(fragment);
}

public void updateUI() {
for (PreloadItemFragment fragment : fragmentList) {
fragment.updateUI();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.android.gms.example.apidemo.preloading;

import static com.google.android.gms.example.apidemo.MainActivity.LOG_TAG;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import com.google.android.gms.ads.appopen.AppOpenAd;
import com.google.android.gms.example.apidemo.R;
import com.google.android.gms.example.apidemo.databinding.FragmentPreloadItemBinding;

/** A [Fragment] subclass that preloads an app open ad. */
public class AppOpenFragment extends PreloadItemFragment {

// Replace this test ad unit ID with your own ad unit ID.
public static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/9257395921";

private FragmentPreloadItemBinding viewBinding;

@Override
public View onCreateView(
@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
viewBinding = FragmentPreloadItemBinding.inflate(inflater, container, false);

// Initialize the UI.
initializeUI();

return viewBinding.getRoot();
}

private void initializeUI() {
viewBinding.txtTitle.setText(getText(R.string.preload_title));
viewBinding.btnShow.setOnClickListener(
view -> {
pollAndShowAd();
updateUI();
});
updateUI();
}

private void pollAndShowAd() {
// Verify that a preloaded ad is available before polling for an ad.
if (!AppOpenAd.isAdAvailable(requireContext(), AD_UNIT_ID)) {
Log.w(LOG_TAG, "Preloaded app open ad ${AD_UNIT_ID} is not available.");
return;
}
// Polling returns the next available ad and load another ad in the background.
AppOpenAd ad = AppOpenAd.pollAd(requireContext(), AD_UNIT_ID);
Activity activity = getActivity();
if (activity != null && ad != null) {
ad.show(activity);
}
}

@Override
public synchronized void updateUI() {
if (AppOpenAd.isAdAvailable(requireContext(), AD_UNIT_ID)) {
viewBinding.txtStatus.setText(getString(R.string.preload_available));
viewBinding.btnShow.setEnabled(true);
} else {
viewBinding.txtStatus.setText(getString(R.string.preload_exhausted));
viewBinding.btnShow.setEnabled(false);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.android.gms.example.apidemo.preloading;

import static com.google.android.gms.example.apidemo.MainActivity.LOG_TAG;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import com.google.android.gms.ads.interstitial.InterstitialAd;
import com.google.android.gms.example.apidemo.R;
import com.google.android.gms.example.apidemo.databinding.FragmentPreloadItemBinding;

/** A [Fragment] subclass that preloads an interstitial ad. */
public class InterstitialFragment extends PreloadItemFragment {

// Replace this test ad unit ID with your own ad unit ID.
public static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/1033173712";

private FragmentPreloadItemBinding viewBinding;

@Override
public View onCreateView(
@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
viewBinding = FragmentPreloadItemBinding.inflate(inflater, container, false);

// Initialize the UI.
initializeUI();

return viewBinding.getRoot();
}

private void initializeUI() {
viewBinding.txtTitle.setText(getText(R.string.preload_interstitial));
viewBinding.btnShow.setOnClickListener(
view -> {
pollAndShowAd();
updateUI();
});
updateUI();
}

// [START pollAndShowAd]
private void pollAndShowAd() {
// [START isAdAvailable]
// Verify that a preloaded ad is available before polling for an ad.
if (!InterstitialAd.isAdAvailable(requireContext(), AD_UNIT_ID)) {
Log.w(LOG_TAG, "Preloaded interstitial ad ${AD_UNIT_ID} is not available.");
return;
}
// [END isAdAvailable]
// Polling returns the next available ad and load another ad in the background.
InterstitialAd ad = InterstitialAd.pollAd(requireContext(), AD_UNIT_ID);
Activity activity = getActivity();
if (activity != null && ad != null) {
ad.show(activity);
}
}

// [END pollAndShowAd]

@Override
public synchronized void updateUI() {
if (InterstitialAd.isAdAvailable(requireContext(), AD_UNIT_ID)) {
viewBinding.txtStatus.setText(getString(R.string.preload_available));
viewBinding.btnShow.setEnabled(true);
} else {
viewBinding.txtStatus.setText(getString(R.string.preload_exhausted));
viewBinding.btnShow.setEnabled(false);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.android.gms.example.apidemo.preloading;

import androidx.fragment.app.Fragment;

/** Abstract fragment for displaying the UI for a single ad preload format. */
public abstract class PreloadItemFragment extends Fragment {
/** Updates the UI for the fragment. */
public abstract void updateUI();
}
Loading

0 comments on commit d5b16e0

Please sign in to comment.