Android中加入Google廣告

Android的開放造成了很多盜版問題的存在,身為開發人員,很慶幸Google有提供廣告服務這樣的收入方式,雖然並不是很好使用拉,而且隨著系統的進步,似乎已經可以把單個App的某個granted權限給收回來...似乎是廣告的殺手....不過這不在今天的討論範圍。
下面是實作於我的App中的一段呼叫廣告的做法,給有需要的人參考拉 :D


Task Before:
1. Have a Admob account: https://www.admob.com/
2. Register your application: (Recommend to use "Use Google AdSense to improve fill rate....")



Start Coding:
1. Import Admob library:
PATH: $android-sdk/google-admob_ads_sdk/GoogleAdMobAdsSdk-4.0.4.jar

2. AndroidManifast.xml中加入:
<!-- Activity for AdSense -->
<activity android:name="com.google.ads.AdActivity"
    android:configChanges="keyboard|keyboardHidden|orientation"/>

<!-- Permission for AdSense -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>

3. New Ads help class:
import android.app.Activity;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
public class AdSenseUtil {
public static boolean isTest = false; /*Befor deploy, please use true for test*/
public static void addAdSense(Activity act, int adview){
    // Look up the AdView as a resource and load a request.
    AdView adView = (AdView) act.findViewById(adview);
   AdRequest request = new AdRequest();
   
   if(isTest)
    request.setTesting(true);
   
   adView.loadAd(request);
}
}

4. Add Ads component to layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#00000000"
    xmlns:ads="http://schemas.android.com/apk/res/com.shenming.quicklock"      <--Your package name
    >
    
  <ScrollView 
android:id="@+id/ScrollView01" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content">

<TableLayout android:id="@+id/TableLayout01"
android:layout_width="fill_parent" 
android:layout_height="fill_parent"
android:stretchColumns="1">
<TableRow android:layout_gravity="center">
<com.google.ads.AdView android:id="@+id/adViewinconfig"        <--Ads component
           android:layout_width="fill_parent"
           android:layout_height="wrap_content" 
    android:layout_span="4"
           ads:adUnitId="a14df83af3d391d"                                                   <--The id is list in the Admob Site & App page
           ads:adSize="BANNER"
    android:layout_alignParentBottom="true"/>
</TableRow>
.....(Skip)

5. Add Ads call code to Activity...
// Google AdSense
AdSenseUtil.addAdSense(this, R.id.adViewinconfig);

6. You can test your app and ads