Skip to content

Instantly share code, notes, and snippets.

@loretoparisi
Created June 26, 2012 19:37
Show Gist options
  • Save loretoparisi/2998316 to your computer and use it in GitHub Desktop.
Save loretoparisi/2998316 to your computer and use it in GitHub Desktop.
Android MoPub Implementation
package com.designfuture.music.util;
import java.util.HashMap;
import java.util.Map;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.beintoo.main.Beintoo;
import com.beintoo.main.Beintoo.BGetVgoodListener;
import com.beintoo.wrappers.VgoodChooseOne;
import com.designfuture.framework.util.ConnectivityHelper;
import com.designfuture.framework.util.LogHelper;
import com.designfuture.framework.util.UIUtils;
import com.designfuture.music.global.Global;
import com.designfuture.music.global.MXMConfig;
import com.designfuture.music.model.MXMCacheImageUrl;
import com.google.ads.AdSize;
import com.inmobi.androidsdk.IMAdListener;
import com.inmobi.androidsdk.IMAdRequest;
import com.inmobi.androidsdk.IMAdRequest.ErrorCode;
import com.inmobi.androidsdk.IMAdView;
import com.inmobi.androidsdk.IMSDKUtil;
import com.inneractive.api.ads.InneractiveAd;
import com.inneractive.api.ads.InneractiveAdView;
import com.mopub.mobileads.MoPubView;
import com.mopub.mobileads.MoPubView.OnAdFailedListener;
import com.mopub.mobileads.MoPubView.OnAdLoadedListener;
import com.mopub.mobileads.MoPubView.OnAdWillLoadListener;
public class MopubHelper {
public static enum AdNetworkInfo {
UNKNOWN_BANNER("unknown", "banner"),
UNKNOWN_INTERSTITIAL("unknown", "interstitial"),
MILLENNIAL_BANNER("millennial", "banner"),
MILLENNIAL_INTERSTITIAL("millennial", "interstitial"),
ADMOB_BANNER("admob", "banner"),
ADMOB_INTERSTITIAL("admob", "interstitial"),
INMOBI_BANNER("inmobi", "banner"),
INMOBI_INTERSTITIAL("inmobi", "interstitial"),
INNERACTIVE_BANNER("inneractive", "banner"),
INNERACTIVE_INTERSTITIAL("inneractive", "interstitial"),
BEINTOO_BANNER("beintoo", "banner"),
BEINTOO_INTERSTITIAL("beintoo", "interstitial"),
;
private final String adNetwork;
private final String bannerType;
private AdNetworkInfo(String adNetwork, String bannerType) {
this.adNetwork = adNetwork;
this.bannerType = bannerType;
}
public String getNetworkName() {
return adNetwork;
}
public String getBannerType() {
return bannerType;
}
}
public interface MoPubEventsListener{
public void onAdWillLoad( MoPubView adView, AdNetworkInfo adNetwork );
public void onAdFailedToLoad( MoPubView adView, AdNetworkInfo adNetwork );
public void onAdLoaded( MoPubView adView, AdNetworkInfo adNetwork );
}
private static String TAG = "MopubHelper";
private static MopubHelper instance;
private static int MAX_CONSECUTIVE_FAIL = 10;
private int failCount = 0;
private MoPubEventsListener mPrivateListener;
private MoPubEventsListener mListener;
private AdsReceiver mMessageReceiver = new AdsReceiver();
/**
* NB: questa soluzione funziona solamente se c'è un unico banner nella activity. Il problema è che nel reciever dobbiamo sapere su quale MoPubView chiamare gli eventi
* ma un recieve per definizione riceve i messaggi inviati da tutte le inner-active che stanno mandando messaggi in broadcast quindi ammeno di non avere dei parametri
* nell'intent per sapere quale view richiamare, non possiamo fare niente
*
*/
private class AdsReceiver extends BroadcastReceiver {
/**
IaAdReceived // Called when a new paid Ad has been received and is about to be displayed.
IaDefaultAdReceived - Called when a new default Ad has been received and is about to be displayed.
IaAdFailed - Called when an Ad request fails to get an Ad.
IaAdClicked - Called when an Ad clicked.
IaAdResize - Called when an Ad resized.
IaAdResizeClosed - Called when an Ad resize closed.
IaAdExpand - Called when an Ad expanded.
IaAdExpandClosed - Called when an Ad expand closed.
IaAdReceived ---> customEventDidLoadAd
IaDefaultAdReceived ---> customEventDidLoadAd
IaAdFailed ---> customEventDidFailToLoadAd
IaAdClicked ---> customEventActionWillBegin
[NO MAPPING] ---> customEventWillLoad // only necessary when pre-caching an ad, specifically an interstitial.
IaAdResize // Called when an Ad resized.
IaAdResizeClosed --> CustomEventActionDidEnd
IaAdExpand --> [NO MAPPING]
IaAdExpandClosed --> CustomEventActionDidEnd/
*/
private String INNER_ACTIVE_AD_FAIL = "IaAdFailed";
private String INNER_ACTIVE_AD_RECIVED = "IaAdReceived";
private String INNER_ACTIVE_AD_DEFAULT_RECIVED = "IaDefaultAdReceived";
private String INNER_ACTIVE_AD_CLICKED = "IaAdClicked";
private String INNER_ACTIVE_AD_RESIZE = "IaAdResize";
private String INNER_ACTIVE_AD_RESIZE_CLOSED = "IaAdResizeClosed";
private String INNER_ACTIVE_AD_EXPAND = "IaAdExpand";
private String INNER_ACTIVE_AD_EXPAND_CLOSED = "IaAdExpandClosed";
private MoPubView adView;
public void setAdView( MoPubView adView ){
this.adView = adView;
}
@Override
public void onReceive(Context context, Intent intent) {
LogHelper.i(TAG, "AdsReceiver onReceive ----> !!! " + intent.getStringExtra("message") );
if(adView == null){
LogHelper.i(TAG, "AdsReceiver: an AdView hasn't been setted");
return;
}
String message = intent.getStringExtra("message");
if( INNER_ACTIVE_AD_FAIL.equals(message) ){
adFailedToRecive(adView, AdNetworkInfo.INNERACTIVE_BANNER);
}else if( INNER_ACTIVE_AD_RECIVED.equals(message) ) {
adLoaded(adView, null, AdNetworkInfo.INNERACTIVE_BANNER);
}else if( INNER_ACTIVE_AD_DEFAULT_RECIVED.equals(message) ) {
adLoaded(adView, null, AdNetworkInfo.INNERACTIVE_BANNER);
}else if( INNER_ACTIVE_AD_CLICKED.equals(message) ) {
adView.customEventActionWillBegin();
}
}
}
public static MopubHelper getInstance() {
if (instance == null)
instance = new MopubHelper();
return instance;
}
public MopubHelper() {
}
public MopubHelper(Context context) {
IntentFilter filterList = new IntentFilter();
filterList.addAction("InneractiveAd");
}
/**
* with this function general listener can be settet to the helper
*
* @param listener
*/
public void setListener( MoPubEventsListener listener ){
mListener = listener;
}
/**
* metodo utilizzato da chi vuole l'ads, i fragment dovranno solo richiamare
* questo metodo e inserire la view restituita all'interno di un layout
*
* @param activity
* @param connected
* @return
*/
public MoPubView createMoPubView(Activity activity, boolean connected) {
if (activity == null || !connected)
return null;
failCount = 0;
MoPubView adView = initMoPubView(activity);
boolean isWifiEnabled = ConnectivityHelper.isWiFiConnected(activity);
boolean isMoPubCampaignEnabled = (Boolean) MXMConfig.getConfigValue(MXMConfig.CONFIG_KEYS.MOPUB_CAMPAIGN_ENABLED);
if (isMoPubCampaignEnabled) { // controllo il flag della config sullo stato delle campagne
String mopubMNC = (String) MXMConfig.getConfigValue(MXMConfig.CONFIG_KEYS.MOPUB_MNC);
String parameters = "mnc:" + mopubMNC;
parameters += ",wifi:" + isWifiEnabled; // isWifiEnabled è il flag tornato dal check sul Wifi
adView.setKeywords(parameters); // aggiungo le chiavi
}
//commentato perché viene avviato esternamente
//adView.loadAd();
return adView;
}
/**
* it works only if the banner takes all the screen width
*
* @param activity
* @return
*/
private boolean isLeaderboard(Activity activity){
if(!UIUtils.isTablet(activity))
return false;
Display display = activity.getWindowManager().getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
int display_w = (int) ((display.getWidth()/metrics.density)+0.5);
return (display_w > AdSize.IAB_LEADERBOARD.getWidth() );
}
private MoPubView initMoPubView(Activity activity) {
LogHelper.i(TAG, "new ADS");
MoPubView adView = new MoPubView(activity);
IntentFilter filterList = new IntentFilter();
filterList.addAction("InneractiveAd");
//viene impostato la adView sulla quale fare le richieste
mMessageReceiver.setAdView(adView);
LocalBroadcastManager.getInstance(activity).registerReceiver( mMessageReceiver , new IntentFilter("InneractiveAd") );
mPrivateListener = new MoPubEventsListener() {
public void onAdWillLoad( MoPubView view, AdNetworkInfo adNetwork ) {
LogHelper.i(TAG,"MoPubEventsListener: AD WILL LOAD, Network " + adNetwork.getNetworkName() + " - Type " + adNetwork.getBannerType() );
if(mListener != null)
mListener.onAdWillLoad( view, adNetwork );
}
@Override
public void onAdLoaded( MoPubView view, AdNetworkInfo adNetwork ) {
LogHelper.i(TAG,"MoPubEventsListener: AD LOADED, Network " + adNetwork.getNetworkName() + " - Type " + adNetwork.getBannerType() );
if(mListener != null)
mListener.onAdLoaded( view, adNetwork );
}
@Override
public void onAdFailedToLoad( MoPubView view, AdNetworkInfo adNetwork ) {
LogHelper.i(TAG,"MoPubEventsListener: AD FAILED TO LOAD, Network " + adNetwork.getNetworkName() + " - Type " + adNetwork.getBannerType() );
if(mListener != null)
mListener.onAdFailedToLoad( view, adNetwork );
}
};
adView.setBackgroundResource(android.R.color.transparent);
adView.setAdUnitId(isLeaderboard(activity) ? Global.MOPUP_TABLET_PUBLISHER_ID : Global.MOPUP_BANNER_PUBLISHER_ID);
LogHelper.i(TAG, "initMoPubView: richiesta con ID " + (isLeaderboard(activity) ? Global.MOPUP_TABLET_PUBLISHER_ID : Global.MOPUP_BANNER_PUBLISHER_ID) );
adView.setOnAdLoadedListener(new OnAdLoadedListener() {
@Override
public void OnAdLoaded(MoPubView view) {
//LogHelper.e(TAG,"MoPub: AD LOADED");
AdNetworkInfo info = AdNetworkInfo.UNKNOWN_BANNER;
try {
info = (AdNetworkInfo) view.getTag();
} catch ( Exception e ) {
info = AdNetworkInfo.UNKNOWN_BANNER;
} finally {
if ( info == null )
info = AdNetworkInfo.UNKNOWN_BANNER;
}
if(mPrivateListener != null)
mPrivateListener.onAdLoaded(view, info);
failCount = 0;
}
});
adView.setOnAdFailedListener(new OnAdFailedListener() {
@Override
public void OnAdFailed(MoPubView view) {
//LogHelper.e(TAG, "MoPub: AD FAILD TO LOAD");
failCount++;
if (failCount < MAX_CONSECUTIVE_FAIL)
view.loadAd();
AdNetworkInfo info = AdNetworkInfo.UNKNOWN_BANNER;
try {
info = (AdNetworkInfo) view.getTag();
} catch ( Exception e ) {
info = AdNetworkInfo.UNKNOWN_BANNER;
} finally {
if ( info == null )
info = AdNetworkInfo.UNKNOWN_BANNER;
}
if(mPrivateListener != null)
mPrivateListener.onAdFailedToLoad(view, info);
}
});
adView.setOnAdWillLoadListener(new OnAdWillLoadListener() {
@Override
public void OnAdWillLoad(MoPubView view, String url) {
//LogHelper.e(TAG, "MoPub: AD WILL LOAD");
AdNetworkInfo info = AdNetworkInfo.UNKNOWN_BANNER;
try {
info = (AdNetworkInfo) view.getTag();
} catch ( Exception e ) {
info = AdNetworkInfo.UNKNOWN_BANNER;
} finally {
if ( info == null )
info = AdNetworkInfo.UNKNOWN_BANNER;
}
if(mPrivateListener != null)
mPrivateListener.onAdWillLoad(view, info);
}
});
return adView;
}
protected void adLoaded(MoPubView adView, View child, AdNetworkInfo adInfo) {
// Signal to our MoPubView that the custom event successfully loaded an
// AdMob ad.
adView.customEventDidLoadAd();
// Place the AdView into our MoPubView. Inneractive setAdContentView before the success callback so it won't send a child to set on this call
if(child != null )
adView.setAdContentView(child);
failCount = 0;
if( mPrivateListener != null )
mPrivateListener.onAdLoaded( adView, adInfo );
}
protected void adFailedToRecive(MoPubView adView, AdNetworkInfo adInfo) {
LogHelper.i(TAG, adView.getTag() + ": adFailedToRecive");
LogHelper.i(TAG, "failCount" + failCount);
if (failCount < MAX_CONSECUTIVE_FAIL)
adView.customEventDidFailToLoadAd();
if( mPrivateListener != null )
mPrivateListener.onAdFailedToLoad( adView, adInfo );
}
public void loadMadvertiseAd(MoPubView adView) {
adView.setTag(adView.getTag() + "loadMadvertiseAd");
LogHelper.i(TAG, adView.getTag() + ": loadMadvertiseAd");
// dovrebbe bastare fare questo:
// https://redmine.madvertise.me/projects/madapi/wiki/Android_SDK
//new MadvertiseHelper(AdView);
}
/**
* mopub custom event method for Beingintoo
*/
public void loadBeintooAd(final MoPubView adView) {
LogHelper.i(TAG, "loadBeeintoAd");
Beintoo.setApiKey(Global.BEINTOO_API_KEY);
Activity activity = adView.getActivity();
// Registrazione dell'utente/app
Beintoo.playerLogin(activity);
final LinearLayout layout = new LinearLayout(activity);
//layout.setTag("Inneractive");
layout.setBackgroundResource(android.R.color.transparent);
if(mPrivateListener != null)
mPrivateListener.onAdWillLoad(adView, AdNetworkInfo.BEINTOO_BANNER);
Beintoo.GetVgood(adView.getContext(), null, false, layout, Beintoo.VGOOD_NOTIFICATION_BANNER, new BGetVgoodListener() {
@Override
public void onError() {
adLoaded(adView, layout, AdNetworkInfo.BEINTOO_BANNER);
}
@Override
public void onComplete(VgoodChooseOne v) {
adFailedToRecive(adView, AdNetworkInfo.BEINTOO_BANNER);
}
@Override
public void nothingToDispatch() {
adFailedToRecive(adView, AdNetworkInfo.BEINTOO_BANNER);
}
@Override
public void isOverQuota() {
adFailedToRecive(adView, AdNetworkInfo.BEINTOO_BANNER);
}
});
// Place the adView into our MoPubView.
adView.setAdContentView(layout);
}
public void loadInMobiAd( final MoPubView adView){
LogHelper.i(TAG, adView.getTag() + ": loadInMobiAd");
IMAdView mIMAdview = new IMAdView((Activity) adView.getContext(), ( isLeaderboard(adView.getActivity())? IMAdView.INMOBI_AD_UNIT_728X90 : IMAdView.INMOBI_AD_UNIT_320X50 ), Global.INMOBI_PUBLISHER_ID);
mIMAdview.setLayoutParams(new LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
//set log level, this way the logcat is much more informative
if( Global.isDebuggable() )
IMSDKUtil.setLogLevel(1);
//create the ad request
IMAdRequest adRequest = new IMAdRequest();
//set parameters on request as shown by the inMobi sample
Map<String, String> map = new HashMap<String, String>();
map.put("tp", "c_mopub");
adRequest.setRequestParams(map);
adRequest.setTestMode(false);
mIMAdview.setIMAdRequest(adRequest);
mIMAdview.setIMAdListener(new IMAdListener() {
@Override
public void onShowAdScreen(IMAdView imAdView) {
LogHelper.e("IMOBI", "InMobiAdActivity-> onShowAdScreen, adView: " + imAdView);
adView.customEventActionWillBegin();
if(mPrivateListener != null)
mPrivateListener.onAdWillLoad(adView, AdNetworkInfo.INMOBI_BANNER);
}
@Override
public void onDismissAdScreen(IMAdView imAdView) {
LogHelper.e("IMOBI", "InMobiAdActivity-> onDismissAdScreen, adView: " + imAdView);
}
@Override
public void onAdRequestFailed(IMAdView imAdView, ErrorCode errorCode) {
LogHelper.e("IMOBI", "InMobiAdActivity-> onAdRequestFailed, adView: " + imAdView + " ,errorCode: " + errorCode);
adFailedToRecive(adView, AdNetworkInfo.INMOBI_BANNER);
}
@Override
public void onAdRequestCompleted(IMAdView imAdView) {
LogHelper.e("IMOBI", "InMobiAdActivity-> onAdRequestCompleted, adView: " + imAdView);
adLoaded(adView, imAdView, AdNetworkInfo.INMOBI_BANNER);
}
@Override
public void onLeaveApplication(IMAdView imAdView) {
LogHelper.e("IMOBI", "InMobiAdActivity-> onLeaveApplication, adView: " + imAdView);
}
});
//load ads
mIMAdview.loadNewAd();
//Set Auto refresh off
mIMAdview.setRefreshInterval(IMAdView.REFRESH_INTERVAL_OFF);
}
public void loadInneractiveAd(MoPubView adView) {
LogHelper.i(TAG, adView.getTag() + ": loadInneractiveAd");
try {
Activity activity = adView.getActivity();
android.webkit.WebViewDatabase webViewDB = android.webkit.WebViewDatabase.getInstance(activity);
if (webViewDB == null) {
adFailedToRecive(adView, AdNetworkInfo.INNERACTIVE_BANNER);
return;
}
FrameLayout layout = new FrameLayout(activity);
//layout.setTag("Inneractive");
layout.setBackgroundResource(android.R.color.transparent);
if(mPrivateListener != null)
mPrivateListener.onAdWillLoad(adView, AdNetworkInfo.INNERACTIVE_BANNER);
//display inner-active banner
if (!InneractiveAd.displayAd(activity, layout, Global.INNERACTIVE_PUBLISHER_ID, InneractiveAd.IaAdType.Banner, 0))
adFailedToRecive(adView, AdNetworkInfo.INNERACTIVE_BANNER);
else {
RelativeLayout relative = (RelativeLayout) layout.getChildAt(0);
InneractiveAdView ad = (InneractiveAdView) relative.getChildAt(0);
ad.setRefreshInterval(-1);
if (!UIUtils.isBeforeHoneycomb())
ad.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
// Place the AdView into our MoPubView. now because I won't have the layout into the reciever
adView.setAdContentView(layout);
}
} catch (Exception e) {
//e.printStackTrace();
adFailedToRecive(adView, AdNetworkInfo.INNERACTIVE_BANNER);
}
}
/*
private class MadvertiseHelper implements MadvertiseViewCallbackListener {
private MoPubView adView;
public MadvertiseHelper(MoPubView view) {
if (view == null)
return;
this.adView = view;
LayoutInflater inflater = (LayoutInflater) view.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
MadvertiseView madvertiseView = (MadvertiseView) inflater.inflate(UIUtils.isTablet(view.getContext()) ? R.layout.madvertise_leaderboard : R.layout.madvertise_ads, null);
madvertiseView.setMadvertiseViewCallbackListener(this);
}
@Override
public void onLoaded(boolean succeed, MadvertiseView madView) {
LogHelper.i(TAG, "MAdvertiseHelper.onLoaded: succeed: " + succeed);
// LogHelper.i(TAG, "MAdvertiseHelper.onLoaded: succeed: " +
// madView.);
if (madView != null && madView.getChildAt(0) != null && !UIUtils.isBeforeHoneycomb())
((WebView) madView.getChildAt(0)).setLayerType(View.LAYER_TYPE_SOFTWARE, null);
if (succeed)
adLoaded(adView, madView);
else
adFailedToRecive(adView);
}
@Override
public void onError(Exception exception) {
LogHelper.i(TAG, "MAdvertiseHelper.onError");
adFailedToRecive(adView);
}
@Override
public void onIllegalHttpStatusCode(int statusCode, String message) {
LogHelper.i(TAG, "MAdvertiseHelper.onIllegalHttpStatusCode: status: " + statusCode + " - message: " + message);
// adManager.mAdView.rotateThreadedNow();
}
@Override
public void onAdClicked() {
}
@Override
public void onApplicationPause() {
}
@Override
public void onApplicationResume() {
}
}
*/
/*
* public void loadBurstlyAd( MoPubView AdView ){ BurstlyView mBanner = new
* BurstlyView(AdView.getActivity());
*
* mBanner.setPublisherId(Global.BURSTLY_PUBLISHER_ID);
* mBanner.setZoneId("0358993469106294955");
* mBanner.setBurstlyViewId("bannerBurstlyView");
* mBanner.setDefaultSessionLife(30);
*
* mBanner.sendRequestForAd();
*
* mBanner.setBurstlyAdListener(new BurstlyHelper()); }
*
* private class BurstlyHelper implements IBurstlyAdListener{
*
* @Override public void onCollapse() { // TODO Auto-generated method stub
*
* }
*
* @Override public void onExpand(boolean arg0) { // TODO Auto-generated
* method stub
*
* }
*
* @Override public void onHide() { // TODO Auto-generated method stub
*
* }
*
* @Override public void onShow() { // TODO Auto-generated method stub
*
* }
*
* @Override public void viewDidChangeSize(AdSize arg0, AdSize arg1) { //
* TODO Auto-generated method stub
*
* }
*
* @Override public void adNetworkDismissFullScreen(String arg0) { // TODO
* Auto-generated method stub
*
* }
*
* @Override public void adNetworkPresentFullScreen(String arg0) { // TODO
* Auto-generated method stub
*
* }
*
* @Override public void adNetworkWasClicked(String arg0) { // TODO
* Auto-generated method stub
*
* }
*
* @Override public void attemptingToLoad(String arg0) { LogHelper.i(TAG +
* ".BurstlyHelper","attemptingToLoad"); }
*
* @Override public void didLoad(String arg0, boolean arg1) {
* LogHelper.i(TAG + ".BurstlyHelper","didLoad");
*
* }
*
* @Overridewidth public void didPrecacheAd(String arg0) { // TODO
* Auto-generated method stub
*
* }
*
* @Override public void failedToDisplayAds() { LogHelper.i(TAG +
* ".BurstlyHelper","failedToDisplayAds");
*
* }
*
* @Override public void failedToLoad(String arg0) { LogHelper.i(TAG +
* ".BurstlyHelper","failedToLoad");
*
* }
*
* @Override public void finishRequestToServer() { // TODO Auto-generated
* method stub
*
* }
*
* @Override public void requestThrottled(int arg0) { // TODO Auto-generated
* method stub
*
* }
*
* @Override public void startRequestToServer() { // TODO Auto-generated
* method stub
*
* }
*
* }
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment