1. In app/build.gradle, add the following in the dependencies (Note: for Google Mobile Ads SDK version 17.0.0, more steps will be needed.):
implementation 'com.google.android.gms:play-services-ads:16.0.0'
2. Create an AdsBanner class:
import android.content.Context;
import android.view.ViewGroup.LayoutParams;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
public class AdsBanner {
private static final String AD_ID = "ca-app-pub-3940256099942544/6300978111"; // Banner Test Admob ID
private AdView mAdView;
public AdsBanner(Context context) {
mAdView = new AdView(context);
mAdView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
mAdView.setAdSize(AdSize.SMART_BANNER);
mAdView.setAdUnitId(AD_ID);
}
public AdView getAdView() {
return mAdView;
}
public void load() {
if (mAdView != null) {
AdRequest adRequest = new AdRequest.Builder()
//.addTestDevice(TEST_DEV_HASH)
.build();
mAdView.loadAd(adRequest);
}
}
}
3. Add a layout widget as the banner ads container to the Activity:
<LinearLayout
android:id="@+id/adLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
4. Add the following code in the onCreate() method of the Activity to show the banner ads:
// create AdsBanner unit and append it to the layout.
AdsBanner adsBanner = new AdsBanner(this);
LinearLayout llayout = findViewById(R.id.adLayout);
llayout.addView(adsBanner.getAdView());
adsBanner.load();
Monday, May 6, 2019
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment