简体   繁体   English

如何将Google Ads集成到Android应用程序中?

[英]How to integrate Google Ads in Android application?

I'm integrating Google Ads in Android application. 我正在将Google Ads集成到Android应用程序中。 I'm implementing example of google ad mob, which I have getting example from the net. 我正在实施google ad mob的示例,该示例已从网上获得。 And also I have add external jar file of google-play-service_lib.jar and add the element of 而且我还添加了google-play-service_lib.jar的外部jar文件,并添加了

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

And when I run the app the application is crashes. 当我运行该应用程序时,该应用程序崩溃了。 I'm getting error like this: 我收到这样的错误:

= 04-15 12:16:33.713: W/Ads(545): Invalid unknown request error: Cannot determine request type. = 04-15 12:16:33.713:W / Ads(545):无效的未知请求错误:无法确定请求类型。 Is your ad unit id correct? 您的广告单元ID是否正确? There was a problem getting an ad response. 收到广告回应时出现问题。 ErrorCode: 1 Failed to load ad: 1 04-15 12:16:04.713: W/GooglePlayServicesUtil(545): Google Play services is missing. 错误代码:1无法加载广告:1 04-15 12:16:04.713:W / GooglePlayServicesUtil(545):缺少Google Play服务。

Here is my code. 这是我的代码。

The code of BannerAdListener 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;
  }

}

Here is manifest file 这是清单文件

<?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>

And the log cat Information is here. 日志猫信息在这里。

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

You need to provide your AdUnitId. 您需要提供您的 AdUnitId。

  private static final String AD_UNIT_ID = "INSERT_YOUR_AD_UNIT_ID_HERE";

Is not a valid AdUnitId. 不是有效的AdUnitId。 Go to your Admob dashboard and get your AdunitId and plug it into the code above. 转到Admob信息中心,获取AdunitId并将其插入上面的代码中。

I was working with Google Ads and this is a basic example 我正在使用Google Ads,这是一个基本示例

This is my AndroidManifest.xml 这是我的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>

I was working with the last version of GooglePlay Services , so this is my integers.xml 我正在使用最新版本的GooglePlay Services ,所以这是我的integers.xml

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

This is my "test" activity, I've got from a sdk example: 这是我的“测试”活动,来自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();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM