如何在Android应用程序中集成G​​oogle广告?

时间:2014-04-15 06:53:37

标签: java android admob

我正在Android应用中集成Google广告。我正在实施谷歌广告暴徒的例子,我从网上得到了一些例子。我还添加了google-play-service_lib.jar的外部jar文件并添加

元素
<activity android:name="com.google.ads.AdActivity"
              android:configChanges="keyboard|keyboardHidden|orientation"/>
</application>

当我运行应用程序时,应用程序崩溃了。我收到这样的错误:

  

= 04-15 12:16:33.713:W / Ads(545):无效的未知请求错误:无法确定请求类型。您的广告单元ID是否正确?   获得广告响应时出现问题。 ErrorCode:1   无法加载广告:1   04-15 12:16:04.713:W / GooglePlayServicesUtil(545):Google Play服务丢失。

这是我的代码。

BannerAdListener的代码

public class BannerAdListener extends Activity {
  /** Your ad unit id*/
  private static final String AD_UNIT_ID = "INSERT_YOUR_AD_UNIT_ID_HERE";

  /** The log tag. */
  private static final String LOG_TAG = "BannerAdListener";

  /** The view to show the ad. */
  private AdView adView;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Create an ad.
    adView = new AdView(this);
    adView.setAdSize(AdSize.BANNER);
    adView.setAdUnitId(AD_UNIT_ID);

    // Set the AdListener.
    adView.setAdListener(new AdListener() {
      /** Called when an ad is clicked and about to return to the application. */
      @Override
      public void onAdClosed() {
        Log.d(LOG_TAG, "onAdClosed");
        Toast.makeText(BannerAdListener.this, "onAdClosed", Toast.LENGTH_SHORT).show();
      }

      /** Called when an ad failed to load. */
      @Override
      public void onAdFailedToLoad(int error) {
        String message = "onAdFailedToLoad: " + getErrorReason(error);
        Log.d(LOG_TAG, message);
        Toast.makeText(BannerAdListener.this, message, Toast.LENGTH_SHORT).show();
      }

      /**
       * Called when an ad is clicked and going to start a new Activity that will
       * leave the application (e.g. breaking out to the Browser or Maps
       * application).
       */
      @Override
      public void onAdLeftApplication() {
        Log.d(LOG_TAG, "onAdLeftApplication");
        Toast.makeText(BannerAdListener.this, "onAdLeftApplication", Toast.LENGTH_SHORT).show();
      }

      /**
       * Called when an Activity is created in front of the app (e.g. an
       * interstitial is shown, or an ad is clicked and launches a new Activity).
       */
      @Override
      public void onAdOpened() {
        Log.d(LOG_TAG, "onAdOpened");
        Toast.makeText(BannerAdListener.this, "onAdOpened", Toast.LENGTH_SHORT).show();
      }

      /** Called when an ad is loaded. */
      @Override
      public void onAdLoaded() {
        Log.d(LOG_TAG, "onAdLoaded");
        Toast.makeText(BannerAdListener.this, "onAdLoaded", Toast.LENGTH_SHORT).show();
      }
    });    
    // Add the AdView to the view hierarchy.
    LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
    layout.addView(adView);

    // Create an ad request. Check logcat output for the hashed device ID to
    // get test ads on a physical device.
    AdRequest adRequest = new AdRequest.Builder()
        .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
        .addTestDevice("INSERT_YOUR_HASHED_DEVICE_ID_HERE")
        .build();

    // Start loading the ad in the background.
    adView.loadAd(adRequest);
  }

  @Override
  public void onResume() {
    super.onResume();
    if (adView != null) {
      adView.resume();
    }
  }

  @Override
  public void onPause() {
    if (adView != null) {
      adView.pause();
    }
    super.onPause();
  }

  /** Called before the activity is destroyed. */
  @Override
  public void onDestroy() {
    if (adView != null) {
      // Destroy the AdView.
      adView.destroy();
    }
    super.onDestroy();
  }

  /** Gets a string error reason from an error code. */
  private String getErrorReason(int errorCode) {
    String errorReason = "";
    switch(errorCode) {
      case AdRequest.ERROR_CODE_INTERNAL_ERROR:
        errorReason = "Internal error";
        break;
      case AdRequest.ERROR_CODE_INVALID_REQUEST:
        errorReason = "Invalid request";
        break;
      case AdRequest.ERROR_CODE_NETWORK_ERROR:
        errorReason = "Network Error";
        break;
      case AdRequest.ERROR_CODE_NO_FILL:
        errorReason = "No fill";
        break;
    }
    return errorReason;
  }

}

这是清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.google.example.gms.ads.banneradlistener"
          android:versionCode="1"
          android:versionName="1.0">
    <uses-sdk android:minSdkVersion="9"
              android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".BannerAdListener"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name="com.google.android.gms.ads.AdActivity"
          android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
    <meta-data android:name="com.google.android.gms.version"
               android:value="@integer/google_play_services_version" />
    </application>

</manifest>

日志猫信息就在这里。

04-15 12:16:04.473: D/dalvikvm(545): DexOpt: couldn't find field Landroid/content/res/Configuration;.smallestScreenWidthDp
04-15 12:16:04.502: W/dalvikvm(545): VFY: unable to resolve instance field 21
04-15 12:16:04.503: D/dalvikvm(545): VFY: replacing opcode 0x52 at 0x0012
04-15 12:16:04.503: D/dalvikvm(545): VFY: dead code 0x0014-0018 in Lcom/google/android/gms/common/GooglePlayServicesUtil;.b (Landroid/content/res/Resources;)Z
04-15 12:16:04.534: E/dalvikvm(545): Could not find class 'android.support.v4.app.FragmentActivity', referenced from method com.google.android.gms.common.GooglePlayServicesUtil.showErrorDialogFragment
04-15 12:16:04.534: W/dalvikvm(545): VFY: unable to resolve instanceof 132 (Landroid/support/v4/app/FragmentActivity;) in Lcom/google/android/gms/common/GooglePlayServicesUtil;
04-15 12:16:04.543: D/dalvikvm(545): VFY: replacing opcode 0x20 at 0x0008
04-15 12:16:04.563: E/dalvikvm(545): Could not find class 'android.support.v4.app.FragmentActivity', referenced from method com.google.android.gms.common.GooglePlayServicesUtil.showErrorDialogFragment
04-15 12:16:04.563: W/dalvikvm(545): VFY: unable to resolve check-cast 132 (Landroid/support/v4/app/FragmentActivity;) in Lcom/google/android/gms/common/GooglePlayServicesUtil;
04-15 12:16:04.563: D/dalvikvm(545): VFY: replacing opcode 0x1f at 0x000c
04-15 12:16:04.563: I/dalvikvm(545): Could not find method android.app.Activity.getFragmentManager, referenced from method com.google.android.gms.common.GooglePlayServicesUtil.showErrorDialogFragment
04-15 12:16:04.563: W/dalvikvm(545): VFY: unable to resolve virtual method 9: Landroid/app/Activity;.getFragmentManager ()Landroid/app/FragmentManager;
04-15 12:16:04.563: D/dalvikvm(545): VFY: replacing opcode 0x6e at 0x0023
04-15 12:16:04.563: D/dalvikvm(545): VFY: dead code 0x000e-001c in Lcom/google/android/gms/common/GooglePlayServicesUtil;.showErrorDialogFragment (ILandroid/app/Activity;ILandroid/content/DialogInterface$OnCancelListener;)Z
04-15 12:16:04.563: D/dalvikvm(545): VFY: dead code 0x0026-0030 in Lcom/google/android/gms/common/GooglePlayServicesUtil;.showErrorDialogFragment (ILandroid/app/Activity;ILandroid/content/DialogInterface$OnCancelListener;)Z
04-15 12:16:04.713: W/GooglePlayServicesUtil(545): Google Play services is missing.
04-15 12:16:05.428: I/dalvikvm(545): Total arena pages for JIT: 11
04-15 12:16:05.428: I/dalvikvm(545): Total arena pages for JIT: 12
04-15 12:16:05.562: D/dalvikvm(545): DexOpt: --- BEGIN 'ads-1292075482.jar' (bootstrap=0) ---
04-15 12:16:07.143: D/dalvikvm(545): DexOpt: --- END 'ads-1292075482.jar' (success) ---
04-15 12:16:07.165: D/dalvikvm(545): DEX prep '/data/data/com.google.example.gms.ads.banneradlistener/cache/ads-1292075482.jar': unzip in 14ms, rewrite 1622ms
04-15 12:16:07.655: I/Ads(545): Use AdRequest.Builder.addTestDevice("B3EEABB8EE11C2BE770B684D95219ECB") to get test ads on this device.
04-15 12:16:07.674: I/Ads(545): Starting ad request.
04-15 12:16:18.945: W/GooglePlayServicesUtil(545): Google Play services is missing.
04-15 12:16:18.980: E/GooglePlayServicesUtil(545): GooglePlayServices not available due to error 1
04-15 12:16:21.044: D/dalvikvm(545): GC_EXTERNAL_ALLOC freed 343K, 49% free 2925K/5703K, external 2032K/2137K, paused 171ms
04-15 12:16:21.044: D/webviewglue(545): nativeDestroy view: 0x36ab88
04-15 12:16:33.713: W/Ads(545): Invalid unknown request error: Cannot determine request type. Is your ad unit id correct?
04-15 12:16:33.763: W/Ads(545): There was a problem getting an ad response. ErrorCode: 1
04-15 12:16:33.763: W/Ads(545): Failed to load ad: 1
04-15 12:16:33.763: D/BannerAdListener(545): onAdFailedToLoad: Invalid request

2 个答案:

答案 0 :(得分:2)

您需要提供您的 AdUnitId。

  private static final String AD_UNIT_ID = "INSERT_YOUR_AD_UNIT_ID_HERE";

是否为有效的AdUnitId。转到您的Admob信息中心并获取您的AdunitId并将其插入上面的代码中。

答案 1 :(得分:0)

我正在使用Google广告,这是一个基本示例

这是我的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.tunapuisor.banner"
          android:versionCode="1"
          android:versionName="1.0">
    <uses-sdk android:minSdkVersion="9"
              android:targetSdkVersion="18" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>

    <application android:icon="@drawable/ic_launcher" android:label="@string/app_name">
        <activity android:name=".AdPuisorSample "
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.google.android.gms.ads.AdActivity"                      android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:theme="@android:style/Theme.Translucent"/>

    <meta-data android:name="com.google.android.gms.version"
               android:value="@integer/google_play_services_version" />
    </application>

</manifest>

我正在使用GooglePlay Services的最新版本,所以这是我的integers.xml

<resources>    
    <integer name="google_play_services_version">5089000</integer>  
</resources>

这是我的“测试”活动,我来自一个sdk示例:

package com.tunapuisor.banner;

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

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;


public class AdPuisorSample extends Activity {

  private AdView adView;
  private static final String AD_UNIT_ID = "INSERT_YOUR_AD_UNIT_ID_HERE";

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Create an ad.
    adView = new AdView(this);
    adView.setAdSize(AdSize.BANNER);
    adView.setAdUnitId(AD_UNIT_ID);
    // Add the AdView to the view hierarchy. The view will have no size
    // until the ad is loaded.
    LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
    layout.addView(adView);
    // Create an ad request. Check logcat output for the hashed device ID to
    // get test ads on a physical device.
    AdRequest adRequest = new AdRequest.Builder()
        .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
        .addTestDevice("INSERT_YOUR_HASHED_DEVICE_ID_HERE")
        .build();
    // Start loading the ad in the background.
    adView.loadAd(adRequest);
  }

  @Override
  public void onResume() {
    super.onResume();
    if (adView != null) {
      adView.resume();
    }
  }

  @Override
  public void onPause() {
    if (adView != null) {
      adView.pause();
    }
    super.onPause();
  }

  /** Called before the activity is destroyed. */
  @Override
  public void onDestroy() {
    // Destroy the AdView.
    if (adView != null) {
      adView.destroy();
    }
    super.onDestroy();
  }
}