public void onAdFetchFailure() {
   Log.d("MoPub", "AdSense failed. Trying another");
   MoPubView view = mMoPubViewReference.get();
   if (view != null) {
     view.loadFailUrl();
   }
 }
  @Override
  public void onBannerCollapsed() {
    if (isInvalidated()) return;

    mMoPubView.setAutorefreshEnabled(mStoredAutorefresh);
    mMoPubView.adClosed();
  }
 public void onClickAd() {
   Log.d("MoPub", "AdSense clicked");
   MoPubView view = mMoPubViewReference.get();
   if (view != null) {
     view.registerClick();
   }
 }
  @Override
  public void onBannerExpanded() {
    if (isInvalidated()) return;

    mStoredAutorefresh = mMoPubView.getAutorefreshEnabled();
    mMoPubView.setAutorefreshEnabled(false);
    mMoPubView.adPresentedOverlay();
  }
  private int getTimeoutDelayMilliseconds() {
    if (mMoPubView == null
        || mMoPubView.getAdTimeoutDelay() == null
        || mMoPubView.getAdTimeoutDelay() < 0) {
      return DEFAULT_BANNER_TIMEOUT_DELAY;
    }

    return mMoPubView.getAdTimeoutDelay() * 1000;
  }
 @Override
 public void onDestroy() {
   if (mBannerView != null) {
     mBannerView.destroy();
   }
   if (mMrectView != null) {
     mMrectView.destroy();
   }
   super.onDestroy();
 }
Exemple #7
0
    public void execute() {
      AdView adView = mWeakAdView.get();
      if (adView == null || adView.isDestroyed()) {
        return;
      }

      adView.setIsLoading(false);
      MoPubView mpv = adView.mMoPubView;
      mpv.loadNativeSDK(mParamsMap);
    }
  /*
   * Returns the last known location of the device using its GPS and network location providers.
   * May be null if:
   * - Location permissions are not requested in the Android manifest file
   * - The location providers don't exist
   * - Location awareness is disabled in the parent MoPubView
   */
  private Location getLastKnownLocation() {
    LocationAwareness locationAwareness = mMoPubView.getLocationAwareness();
    int locationPrecision = mMoPubView.getLocationPrecision();
    Location result = null;

    if (locationAwareness == LocationAwareness.LOCATION_AWARENESS_DISABLED) {
      return null;
    }

    LocationManager lm = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
    Location gpsLocation = null;
    try {
      gpsLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    } catch (SecurityException e) {
      Log.d("MoPub", "Failed to retrieve GPS location: access appears to be disabled.");
    } catch (IllegalArgumentException e) {
      Log.d("MoPub", "Failed to retrieve GPS location: device has no GPS provider.");
    }

    Location networkLocation = null;
    try {
      networkLocation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    } catch (SecurityException e) {
      Log.d("MoPub", "Failed to retrieve network location: access appears to be disabled.");
    } catch (IllegalArgumentException e) {
      Log.d("MoPub", "Failed to retrieve network location: device has no network provider.");
    }

    if (gpsLocation == null && networkLocation == null) {
      return null;
    } else if (gpsLocation != null && networkLocation != null) {
      if (gpsLocation.getTime() > networkLocation.getTime()) result = gpsLocation;
      else result = networkLocation;
    } else if (gpsLocation != null) result = gpsLocation;
    else result = networkLocation;

    // Truncate latitude/longitude to the number of digits specified by locationPrecision.
    if (locationAwareness == LocationAwareness.LOCATION_AWARENESS_TRUNCATED) {
      double lat = result.getLatitude();
      double truncatedLat =
          BigDecimal.valueOf(lat)
              .setScale(locationPrecision, BigDecimal.ROUND_HALF_DOWN)
              .doubleValue();
      result.setLatitude(truncatedLat);

      double lon = result.getLongitude();
      double truncatedLon =
          BigDecimal.valueOf(lon)
              .setScale(locationPrecision, BigDecimal.ROUND_HALF_DOWN)
              .doubleValue();
      result.setLongitude(truncatedLon);
    }

    return result;
  }
  /*
   * CustomEventBanner.Listener implementation
   */
  @Override
  public void onBannerLoaded(View bannerView) {
    if (isInvalidated()) return;

    if (mMoPubView != null) {
      cancelTimeout();
      mMoPubView.nativeAdLoaded();
      mMoPubView.setAdContentView(bannerView);
      if (!(bannerView instanceof HtmlBannerWebView)) {
        mMoPubView.trackNativeImpression();
      }
    }
  }
  public void onFinishFetchAd() {
    MoPubView view = mMoPubViewReference.get();
    if (view != null) {
      view.removeAllViews();
      mAdView.setVisibility(View.VISIBLE);
      FrameLayout.LayoutParams layoutParams =
          new FrameLayout.LayoutParams(
              FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
      layoutParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
      view.addView(mAdView, layoutParams);

      view.adLoaded();
    }
  }
  private void adDidLoad() {
    Log.i("MoPub", "Ad successfully loaded.");
    mIsLoading = false;
    scheduleRefreshTimerIfEnabled();
    mMoPubView.removeAllViews();
    FrameLayout.LayoutParams layoutParams =
        new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.WRAP_CONTENT,
            FrameLayout.LayoutParams.WRAP_CONTENT,
            Gravity.CENTER);
    mMoPubView.addView(this, layoutParams);

    mMoPubView.adLoaded();
  }
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    final MoPubSampleAdUnit adConfiguration = MoPubSampleAdUnit.fromBundle(getArguments());
    final View view = inflater.inflate(R.layout.banner_detail_fragment, container, false);
    final DetailFragmentViewHolder views = DetailFragmentViewHolder.fromView(view);
    mMoPubView = (MoPubView) view.findViewById(R.id.banner_mopubview);
    hideSoftKeyboard(views.mKeywordsField);

    final String adUnitId = adConfiguration.getAdUnitId();
    views.mDescriptionView.setText(adConfiguration.getDescription());
    views.mAdUnitIdView.setText(adUnitId);
    views.mLoadButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            final String keywords = views.mKeywordsField.getText().toString();
            loadMoPubView(adUnitId, keywords);
          }
        });
    mMoPubView.setBannerAdListener(this);
    loadMoPubView(adUnitId, null);

    return view;
  }
  @Test
  public void loadAd_shouldPropagateLocationInLocalExtras() throws Exception {
    Location expectedLocation = new Location("");
    expectedLocation.setLongitude(10.0);
    expectedLocation.setLongitude(20.1);

    stub(moPubView.getLocation()).toReturn(expectedLocation);
    subject = new CustomEventBannerAdapter(moPubView, CLASS_NAME, null);
    subject.loadAd();

    expectedLocalExtras.put("location", moPubView.getLocation());

    verify(banner)
        .loadBanner(
            any(Context.class), eq(subject), eq(expectedLocalExtras), eq(expectedServerExtras));
  }
  @Test
  public void onBannerCollapsed_shouldRestoreRefreshSettingAndCallAdClosed() throws Exception {
    stub(moPubView.getAutorefreshEnabled()).toReturn(true);
    subject.onBannerExpanded();
    reset(moPubView);
    subject.onBannerCollapsed();
    verify(moPubView).setAutorefreshEnabled(eq(true));
    verify(moPubView).adClosed();

    stub(moPubView.getAutorefreshEnabled()).toReturn(false);
    subject.onBannerExpanded();
    reset(moPubView);
    subject.onBannerCollapsed();
    verify(moPubView).setAutorefreshEnabled(eq(false));
    verify(moPubView).adClosed();
  }
Exemple #15
0
    public void execute() {
      AdView adView = mWeakAdView.get();
      if (adView == null || adView.isDestroyed()) {
        return;
      }

      adView.setIsLoading(false);
      MoPubView moPubView = adView.mMoPubView;

      if (mParamsMap == null) {
        Log.i("MoPub", "Couldn't invoke custom event because the server did not specify one.");
        moPubView.adFailed();
        return;
      }

      moPubView.loadCustomEvent(mParamsMap);
    }
  private void loadMoPubView(MoPubView moPubView, String adUnitId, String keywords) {
    if (moPubView == null) {
      logToast(getActivity(), "Unable to inflate MoPubView from xml.");
      return;
    }

    try {
      validateAdUnitId(adUnitId);
    } catch (IllegalArgumentException exception) {
      logToast(getActivity(), exception.getMessage());
      return;
    }

    moPubView.setBannerAdListener(this);
    moPubView.setAdUnitId(adUnitId);
    moPubView.setKeywords(keywords);
    moPubView.loadAd();
  }
  @Override
  public void onDestroyView() {
    super.onDestroyView();

    if (mMoPubView != null) {
      mMoPubView.destroy();
      mMoPubView = null;
    }
  }
  @Override
  public void onBannerFailed(MoPubErrorCode errorCode) {
    if (isInvalidated()) return;

    if (mMoPubView != null) {
      if (errorCode == null) {
        errorCode = UNSPECIFIED;
      }
      cancelTimeout();
      mMoPubView.loadFailUrl(errorCode);
    }
  }
  @Before
  public void setUp() throws Exception {
    moPubView = mock(MoPubView.class);
    stub(moPubView.getAdTimeoutDelay()).toReturn(null);

    subject = new CustomEventBannerAdapter(moPubView, CLASS_NAME, JSON_PARAMS);

    expectedLocalExtras = new HashMap<String, Object>();
    expectedServerExtras = new HashMap<String, String>();

    banner = CustomEventBannerFactory.create(CLASS_NAME);
  }
Exemple #20
0
    public void execute() {
      AdView adView = mWeakAdView.get();
      if (adView == null || adView.isDestroyed()) {
        return;
      }

      adView.setIsLoading(false);
      MoPubView mpv = adView.mMoPubView;

      if (mHeader == null) {
        Log.i("MoPub", "Couldn't call custom method because the server did not specify one.");
        mpv.loadFailUrl();
        return;
      }

      String methodName = mHeader.getValue();
      Log.i("MoPub", "Trying to call method named " + methodName);

      Class<? extends Activity> c;
      Method method;
      Activity userActivity = mpv.getActivity();
      try {
        c = userActivity.getClass();
        method = c.getMethod(methodName, MoPubView.class);
        method.invoke(userActivity, mpv);
      } catch (NoSuchMethodException e) {
        Log.d(
            "MoPub",
            "Couldn't perform custom method named "
                + methodName
                + "(MoPubView view) because your activity class has no such method");
        mpv.loadFailUrl();
        return;
      } catch (Exception e) {
        Log.d("MoPub", "Couldn't perform custom method named " + methodName);
        mpv.loadFailUrl();
        return;
      }
    }
 private void handleCustomIntentFromUri(Uri uri) {
   mMoPubView.adClicked();
   String action = uri.getQueryParameter("fnc");
   String adData = uri.getQueryParameter("data");
   Intent customIntent = new Intent(action);
   if (adData != null) customIntent.putExtra(EXTRA_AD_CLICK_DATA, adData);
   try {
     getContext().startActivity(customIntent);
   } catch (ActivityNotFoundException e) {
     Log.w(
         "MoPub",
         "Could not handle custom intent: " + action + ". Is your intent spelled correctly?");
   }
 }
  public void loadAd() {
    if (mAdUnitId == null) {
      Log.d(
          "MoPub",
          "Can't load an ad in this ad view because the ad unit ID is null. "
              + "Did you forget to call setAdUnitId()?");
      return;
    }

    if (mLocation == null) mLocation = getLastKnownLocation();

    String adUrl = generateAdUrl();
    mMoPubView.adWillLoad(adUrl);
    loadUrl(adUrl);
  }
  @Test
  public void timeout_withNonNullAdTimeoutDelay_shouldSignalFailureAndInvalidateWithCustomDelay()
      throws Exception {
    stub(moPubView.getAdTimeoutDelay()).toReturn(77);

    subject.loadAd();

    Robolectric.idleMainLooper(77000 - 1);
    verify(moPubView, never()).loadFailUrl(eq(NETWORK_TIMEOUT));
    assertThat(subject.isInvalidated()).isFalse();

    Robolectric.idleMainLooper(1);
    verify(moPubView).loadFailUrl(eq(NETWORK_TIMEOUT));
    assertThat(subject.isInvalidated()).isTrue();
  }
  @Test
  public void timeout_withNegativeAdTimeoutDelay_shouldSignalFailureAndInvalidateWithDefaultDelay()
      throws Exception {
    stub(moPubView.getAdTimeoutDelay()).toReturn(-1);

    subject.loadAd();

    Robolectric.idleMainLooper(CustomEventBannerAdapter.DEFAULT_BANNER_TIMEOUT_DELAY - 1);
    verify(moPubView, never()).loadFailUrl(eq(NETWORK_TIMEOUT));
    assertThat(subject.isInvalidated()).isFalse();

    Robolectric.idleMainLooper(1);
    verify(moPubView).loadFailUrl(eq(NETWORK_TIMEOUT));
    assertThat(subject.isInvalidated()).isTrue();
  }
  public CustomEventBannerAdapter(MoPubView moPubView, String className, String classData) {
    mHandler = new Handler();
    mMoPubView = moPubView;
    mContext = moPubView.getContext();
    mLocalExtras = new HashMap<String, Object>();
    mServerExtras = new HashMap<String, String>();
    mTimeout =
        new Runnable() {
          @Override
          public void run() {
            Log.d("MoPub", "Third-party network timed out.");
            onBannerFailed(NETWORK_TIMEOUT);
            invalidate();
          }
        };

    Log.d("MoPub", "Attempting to invoke custom event: " + className);
    try {
      mCustomEventBanner = CustomEventBannerFactory.create(className);
    } catch (Exception exception) {
      Log.d("MoPub", "Couldn't locate or instantiate custom event: " + className + ".");
      mMoPubView.loadFailUrl(ADAPTER_NOT_FOUND);
      return;
    }

    // Attempt to load the JSON extras into mServerExtras.
    try {
      mServerExtras = Json.jsonStringToMap(classData);
    } catch (Exception exception) {
      Log.d("MoPub", "Failed to create Map from JSON: " + classData + exception.toString());
    }

    mLocalExtras = mMoPubView.getLocalExtras();
    if (mMoPubView.getLocation() != null) {
      mLocalExtras.put("location", mMoPubView.getLocation());
    }
    if (mMoPubView.getAdViewController() != null) {
      mLocalExtras.put(AD_CONFIGURATION_KEY, mMoPubView.getAdViewController().getAdConfiguration());
    }
  }
  @Override
  public void onBannerClicked() {
    if (isInvalidated()) return;

    if (mMoPubView != null) mMoPubView.registerClick();
  }
 private void loadMoPubView(final String adUnitId, final String keywords) {
   mMoPubView.setAdUnitId(adUnitId);
   mMoPubView.setKeywords(keywords);
   mMoPubView.loadAd();
 }
 private void adDidFail() {
   Log.i("MoPub", "Ad failed to load.");
   mIsLoading = false;
   scheduleRefreshTimerIfEnabled();
   mMoPubView.adFailed();
 }
  public void loadAd() {
    MoPubView view = mMoPubViewReference.get();
    if (view == null) {
      return;
    }

    mAdView = new GoogleAdView(view.getContext());

    // The following parameters are required.  Fail if they aren't set
    JSONObject object;
    String pubId;
    String companyName;
    String appName;
    try {
      object = (JSONObject) new JSONTokener(mParams).nextValue();
      pubId = object.getString("Gclientid");
      companyName = object.getString("Gcompanyname");
      appName = object.getString("Gappname");
    } catch (JSONException e) {
      view.adFailed();
      return;
    }

    // The rest of the parameters are optional
    AdSenseSpec.AdType adtype = AdType.TEXT_IMAGE;
    Boolean testState = false;
    String keywords = "";
    String channelId = "";
    try {
      String at = object.getString("Gadtype");
      if (at.equals("GADAdSenseTextAdType")) {
        adtype = AdType.TEXT;
      } else if (at.equals("GADAdSenseImageAdType")) {
        adtype = AdType.IMAGE;
      }
    } catch (JSONException e) {
    }
    try {
      testState = object.getString("Gtestadrequest").equals("1");
    } catch (JSONException e) {
    }
    try {
      keywords = object.getString("Gkeywords");
    } catch (JSONException e) {
    }
    try {
      channelId = object.getString("Gchannelids");
    } catch (JSONException e) {
    }

    if (keywords == null || keywords.equals("")) {
      keywords = "None";
    }

    AdSenseSpec adSenseSpec =
        new AdSenseSpec(pubId) // Specify client ID. (Required)
            .setCompanyName(companyName) // Set company name. (Required)
            .setAppName(appName) // Set application name. (Required)
            .setKeywords(keywords) // Specify keywords.
            .setChannel(channelId) // Set channel ID.
            .setAdType(adtype) // Set ad type to Text.
            // .setExpandDirection(AdSenseSpec.ExpandDirection.TOP)
            .setAdTestEnabled(testState); // Keep

    if (view.getAdWidth() == 300 && view.getAdHeight() == 250) {
      adSenseSpec.setAdFormat(AdFormat.FORMAT_300x250);
    } else {
      adSenseSpec.setAdFormat(AdFormat.FORMAT_320x50);
    }

    mAdView.setAdViewListener(this);
    Log.d("MoPub", "Showing AdSense ad...");

    // The GoogleAdView has to be in the view hierarchy to make a request
    mAdView.setVisibility(View.INVISIBLE);
    view.addView(
        mAdView,
        new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT));

    mAdView.showAds(adSenseSpec);
  }
 private void adDidClose() {
   mMoPubView.adClosed();
 }