上半年的时候抽空探索了一下如何在自己的安卓程序中嵌入广告(可以用来给自己赚点午饭钱),由于前段时间一直非常忙,直到现在才有时间写这篇文章。下面总结一下心得体会和大家分享。
首先要注册一个Admob的帐号。这步大家可以去网上查(有很详细的注册方法)。下载GoogleAdmob的jar包。
然后建立一个基于Android4.0.3的应用程序。在项目下建立名为“libs”的文件夹(由于是Android4.0.3的应用程序,所以需要建立“libs”的文件夹,而不是“lib”)将上一步下载的jar包导入。如下图:
之后在main.xml中加入以下代码:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/tv" android:text="@string/hello" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <LinearLayout android:id="@+id/l1" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > </LinearLayout> </LinearLayout>
之后在AndroidManifest.xml加入以下代码:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.hyc" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="15" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".AdsDemoActivity" 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.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" /> </application> </manifest>最后在Activity文件下加入以下代码:
package com.hyc;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
public class AdsDemoActivity extends Activity {
TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv=(TextView)findViewById(R.id.tv);
tv.setText("hello ad");
LinearLayout layout = (LinearLayout)findViewById(R.id.l1);
AdView adView = new AdView(this, AdSize.BANNER, "XXXXXX")//XXXXX即是你注册的账号
layout.addView(adView);
adView.loadAd(new AdRequest());
}
}
大功告成,运行程序,效果如图: