Android Open Source - Android-Lib-Advertising Ad Service






From Project

Back to project page Android-Lib-Advertising.

License

The source code is released under:

Apache License

If you think the Android project Android-Lib-Advertising listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package android.lib.ad;
//  w  w w.ja va  2s.c o  m
import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.util.DisplayMetrics;
import android.util.Log;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

import com.sec.android.ad.AdHubView;
import com.sec.android.ad.AdNotificationListener;
import com.sec.android.ad.info.AdSize;
import com.sec.android.ad.targeting.UserProfile;

/**
 * Provides unitifed methods to show ads from Google AdMob or Samsung AdHub.
 * <p>{@link AdService} provides a common set of API to manipulate both Google AdMob ads and
 * Samsung AdHub ads.</p>
 * <p>Ads can be customized by calling {@link #setAge(int)}, {@link #setGender(int)} and
 * {@link #addKeywords(String...)}.</p>
 */
public final class AdService {
    /**
     * Callback methods for {@link AdService}.
     */
    public interface AdListener {
        /**
         * Called when a Google AdMob ad is loaded successfully.
         * @param adView An {@link AdView} object that is loaded successfully.
         */
        void onAdLoaded(AdView adView);

        /**
         * Called when a Samsung AdHub ad is loaded successfully.
         * @param adView An {@link AdHubView} object that is loaded successfully.
         */
        void onAdLoaded(AdHubView adView);

        /**
         * Called when a Google AdMob ad has failed to load.
         * <p>See <a>https://developers.google.com/mobile-ads-sdk/docs/admob/intermediate#play-adlistener</a>
         * for the meaning of the error code.</p>
         * @param adView An {@link AdView} object that has failed to load.
         * @param errorCode The error code that caused the failure.
         */
        void onAdFailedToLoad(AdView adView, int errorCode);

        /**
         * Called when a Samsung AdHub ad has failed to load.
         * @param adView An {@link AdHubView} object that has failed to load.
         * @param exception The error that caused the failure.
         */
        void onAdFailedToLoad(AdHubView adView, Exception exception);
    }

    /**
     * Represents the value of the gender of female.
     * @see #setGender(int)
     */
    public static final int GENDER_FEMALE  = AdRequest.GENDER_FEMALE;
    /**
     * Represents the value of the gender of male.
     * @see #setGender(int)
     */
    public static final int GENDER_MALE    = AdRequest.GENDER_MALE;
    /**
     * Represents the value of an unknown gender.
     * @see #setGender(int)
     */
    public static final int GENDER_UNKNOWN = AdRequest.GENDER_UNKNOWN;

    private final Context     context;
    private final Set<String> keywords = new HashSet<String>();

    private String adId;
    private int    age;
    private int    gender = AdService.GENDER_UNKNOWN;

    private AdListener listener;

    /**
     * Creates an instance of {@link AdService} from the given context.
     * @param context The context to create an instance of {@link AdService}.
     */
    public AdService(final Context context) {
        this.context = context;
    }

    /**
     * Sets the ID of Google AdMob AD_UNIT_ID or Samsung AdHub App/Site ID.
     * @param adId The string ID of the ad to display.
     * @return The same {@link AdService} object, for chaining multiple calls into a single statement.
     */
    public AdService setAdId(final String adId) {
        this.adId = adId;

        return this;
    }

    /**
     * Sets the user's age for targeting purposes.
     * <p>Google AdMob SDK does not support setting the age of the user, but supports setting the
     * user's birthday instead. This method will convert the age to an estimated date of birth for
     * Google AdMob SDK.</p>
     * @param age The user age.
     * @return The same {@link AdService} object, for chaining multiple calls into a single statement.
     */
    public AdService setAge(final int age) {
        this.age = age;

        return this;
    }

    /**
     * Sets the user's gender for targeting purposes.
     * <p>Possible values are:
     * <li>
     * <ul>{@link #GENDER_FEMALE}</ul>
     * <ul>{@link #GENDER_MALE}</ul>
     * <ul>{@link #GENDER_UNKNOWN}</ul>
     * </li></p>
     * @param gender The user's gender.
     * @return The same {@link AdService} object, for chaining multiple calls into a single statement.
     */
    public AdService setGender(final int gender) {
        if (gender == AdService.GENDER_FEMALE || gender == AdService.GENDER_MALE || gender == AdService.GENDER_UNKNOWN) {
            this.gender = gender;
        }

        return this;
    }

    /**
     * Adds a keyword or keywords for targeting purposes.
     * @param keywords One or more keywords to set.
     * @return The same {@link AdService} object, for chaining multiple calls into a single statement.
     */
    public AdService addKeywords(final String... keywords) {
        for (final String keyword : keywords) {
            this.keywords.add(keyword);
        }

        return this;
    }

    /**
     * Sets an {@link AdListener} for this {@link AdService}.
     * @param listener The {@link AdListener} to set.
     * @return The same {@link AdService} object, for chaining multiple calls into a single statement.
     * @see AdListener
     */
    public AdService setAdListener(final AdListener listener) {
        this.listener = listener;

        return this;
    }

    /**
     * Starts loading a Google AdMob ad on a background thread. The size of the ad is determined by
     * Google server automatically.
     * <p>Note: There is no exception will be thrown in case of an error. You must attach an
     * {@link AdListener} to this {@link AdService} in order to receive a callback.</p>
     * @param adView The Google AdMob {@link AdView} to load an ad.
     * @see AdListener#onAdLoaded(AdView)
     * @see AdListener#onAdFailedToLoad(AdView, int)
     */
    public void displayAd(final AdView adView) {
        try {
            adView.setAdUnitId(this.adId);
            adView.setAdSize(com.google.android.gms.ads.AdSize.SMART_BANNER);
        } catch (final IllegalStateException e) {
            Log.w(this.getClass().getName(), e.getMessage(), e);

            if (this.listener != null) {
                this.listener.onAdFailedToLoad(adView, AdRequest.ERROR_CODE_INVALID_REQUEST);
            }
        }

        final AdRequest.Builder builder = new AdRequest.Builder();

        if (this.age > 0) {
            final Calendar calendar = Calendar.getInstance();

            calendar.add(Calendar.YEAR, -this.age);

            builder.setBirthday(calendar.getTime());
        }

        if (this.keywords.size() > 0) {
            for (final String keyword : this.keywords) {
                builder.addKeyword(keyword);
            }
        }

        adView.setAdListener(new com.google.android.gms.ads.AdListener() {
            @Override
            public void onAdLoaded() {
                super.onAdLoaded();

                if (AdService.this.listener != null) {
                    AdService.this.listener.onAdLoaded(adView);
                }
            }

            @Override
            public void onAdFailedToLoad(final int errorCode) {
                super.onAdFailedToLoad(errorCode);

                if (AdService.this.listener != null) {
                    AdService.this.listener.onAdFailedToLoad(adView, errorCode);
                }
            }
        });

        adView.loadAd(builder.setGender(this.gender).build());
    }

    /**
     * Starts loading a Samsung AdHub ad on a background thread.
     * <p>Note: There is no exception will be thrown in case of an error. You must attach an
     * {@link AdListener} to this {@link AdService} in order to receive a callback.</p>
     * @param adView The Samsung AdHub {@link AdHubView} to load an ad.
     * @param adSize The size of the ad to load. You can find the best-fit size for the current
     * user view space by calling {@link #getBestFitAdSize(Activity)}.
     * @see AdListener#onAdLoaded(AdHubView)
     * @see AdListener#onAdFailedToLoad(AdHubView, Exception)
     * @see #getBestFitAdSize(Activity)
     */
    public void displayAd(final AdHubView adView, final AdSize adSize) {
        adView.init(this.context, this.adId, adSize);

        final UserProfile profile = new UserProfile();

        profile.setGender(this.gender == AdService.GENDER_FEMALE ? UserProfile.FEMALE : this.gender == AdService.GENDER_MALE ? UserProfile.MALE : UserProfile.UNKNOWN);

        if (this.age > 0) {
            profile.setAge(this.age);
        }

        if (this.keywords.size() > 0) {
            for (final String keyword : this.keywords) {
                profile.setInterests(keyword);
            }
        }

        adView.setUserProfile(profile);

        adView.setListener(new AdNotificationListener() {
            @Override
            public void onAdReceived(final AdHubView adView) {
                if (AdService.this.listener != null) {
                    AdService.this.listener.onAdLoaded(adView);
                }
            }

            @Override
            public void onAdFailed(final AdHubView adView, final Exception exception) {
                if (AdService.this.listener != null) {
                    AdService.this.listener.onAdFailedToLoad(adView, exception);
                }
            }
        });

        adView.startAd();
    }

    /**
     * Returns the best-fit size of an ad to display for the current user view space.
     * @param activity The activity to host the ad.
     * @return The ad size for {@link #displayAd(AdHubView, AdSize)}.
     */
    public static AdSize getBestFitAdSize(final Activity activity) {
        final int            orientation = activity.getResources().getConfiguration().orientation;
        final DisplayMetrics metrics     = new DisplayMetrics();

        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);

        final double xInches    = metrics.widthPixels / metrics.xdpi;
        final double yInches    = metrics.heightPixels / metrics.ydpi;
        final double screenSize = Math.sqrt(xInches * xInches + yInches * yInches);

        AdSize size = com.sec.android.ad.info.AdSize.BANNER_320x50;

        if (screenSize >= activity.getResources().getInteger(R.integer.smallest_tablet_screen_size)) {
            if (orientation == Configuration.ORIENTATION_PORTRAIT) {
                if (metrics.widthPixels >= 640) {
                    size = AdSize.BANNER_640x100;
                } else {
                    size = AdSize.BANNER_320x50;
                }
            } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                if (metrics.heightPixels >= 728) {
                    size = AdSize.TABLET_728x90;
                } else {
                    size = AdSize.BANNER_640x100;
                }
            }
        }

        return size;
    }
}




Java Source Code List

android.lib.ad.AdService.java
android.lib.ad.sample.MainActivity.java