Android: how to integrate admob in app? - android

I was trying to integrate admob banner in my application several hours, but I couldn't do that, so I created new app the only purpose of which is show admob banner but it doesn't work too. here is code
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AdView adView = new AdView(this, AdSize.BANNER, "XXX");
adView.setVisibility(View.VISIBLE);
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams adParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
layout.addView(adView, adParams);
setContentView(layout);
AdRequest adRequest = new AdRequest();
adView.loadAd(adRequest);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
and here is my manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.zzzzzz_admobtest"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.zzzzzz_admobtest.MainActivity"
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>
what am I doing wrong?
Also, when I output adView.isActivated() and adView.isReady() they both are false.
I am using "XXX" instead of ID because I don't have one. Could it be a problem?
I am using device. Here is errors on ligcat
08-07 22:43:04.248: E/ActivityThread(24181): Failed to find provider info for com.google.plus.platform
08-07 22:43:04.454: E/Ads(24181): JS: Uncaught ReferenceError: AFMA_getSdkConstants is not defined (http://media.admob.com/:1)
08-07 22:43:04.454: E/Web Console(24181): Uncaught ReferenceError: AFMA_getSdkConstants is not defined at http://media.admob.com/:1
the last 2 errors could be fixed by this code
(new Thread() {
public void run() {
Looper.prepare();
adView.loadAd(new AdRequest());
}
}).start();
as I understand the first one is not an error but just a warning.
so why this isn't work??

I am using "XXX" instead of ID because I don't have one. Could it be a
problem?
Yes. Absolutely yes. Sign up for an Admob account. Get yourself an ID and use that.

Meta-Data Tag is missing inside the Android-manifest.look into the already available resources Example
<meta-data
android:name="ADMOB_PUBLISHER_ID"
android:value="XXXX" />

This question is kinda old, but I want to answer it, because new technology appeared, which lets AdMob integration really easy. You don't need to code anything additionally in most cases, just create and .apk file and Admob will be injected into it automatically.
Enter FGL Enhance. Select, which SDK to integrate. You can select multiple various SDKs using this service, for this tutorial we'll pick only Admob from "I want to choose SDK myself".
Actually you can integrate more than 20 SDKs available by just selecting their checkbox. This list includes various ads providers, Crash reporting, Dolby Audio, etc.
Select, what development technology was used to build your app. If you want to show/hide the banner, you'll need to connect the lightweight drag-and-drop library and add 1 line of code. Depending on the technology you selected you'll be given a code sample and connector library download link.
But if you just want the banner to be present on your screen all the time, which is the easiest solution, you don't need to change your game code! This solution is called ZeroCode and it works for any development technology: event for the .apk and .ipa, which you've got from an HTML5-game or from Game Maker.
On this page you can select the ads types which will be shown in your app.
Interstitial - ads between the levels
Rewarded Video - videos, with a reward for viewing
Flexible Banner - banner, which can be hidden/shown in the game code
Persistent Banner - banner, which will stay on the screen all the time (but banner rotation is available, from AdMob settings)
Pre-Roll - ads, shown as the app starts (like in ketchapp's games)
Two last types are marked as ZeroCode. You don't need to code anything in your game to have them integrated. For our sample we'll select just a Persistent banner.
Now upload our app.
On the next screen we can select a banner type. We can use, for example SMART_BANNER or any other banner type from AdMob help. We'll also input the banner id from our AdMob account. When creating a banner in AdMob account, we can set refresh interval.
The final step - signing method selection. You ca use your own developer's certificate, then you'll be able to submit the game to the store right after the AdMob has been injected. You can select a testing certificate to test the app on your own device. Or you can download an unsigned app and sign it locally before submitting to the store.
One more progress bar...
And here we are!
The Enhance service is completely free for the developers. You'll receive the same amount of money from ads as if you'd integrated the ads manually. FGL receives the income from the SDK providers, because, in fact, FGL Enhance makes SDKs more attractive for the new developers.
source: http://www.airapport.com/2016/09/tutorial-how-to-quickly-integrate-admob.html

how to integrate AdMob and Facebook banner ads into Android applications
Build.Gradle :
implementation 'com.google.android.gms:play-services-ads:19.1.0'
implementation 'com.facebook.android:audience-network-sdk:5.+'
MyAplication.java:
AudienceNetworkAds.initialize(this);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
Manifest.xml:
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="App_ID_Here.."/> //Test App ID For Testing Purpose.
<activity
android:name="com.facebook.ads.AudienceNetworkActivity"
android:configChanges="keyboardHidden|orientation|screenSize" />
Permission:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
public class MainActivity extends AppCompatActivity {
private LinearLayout bannerView;
//Banner
private AdView facebookAdView;
private com.google.android.gms.ads.AdView admobAdView;
//Interstitial
private InterstitialAd facebookInterstitialAds;
private com.google.android.gms.ads.InterstitialAd adMobInterstitialAds;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bannerView = (LinearLayout) findViewById(R.id.bannerView);
//Load Banner Ads
showFacebookBannerAds();
//Load Interstitial Ads
showFacebookInterstitial();
}
private void showFacebookBannerAds() {
facebookAdView = new AdView(this, "Facebook_Banner_ID", AdSize.BANNER_HEIGHT_50);
bannerView.addView(facebookAdView);
facebookAdView.setAdListener(new AdListener() {
#Override
public void onError(Ad ad, AdError adError) {
//If Load Fail then
showAdMobBanner();
}
#Override
public void onAdLoaded(Ad ad) {
}
#Override
public void onAdClicked(Ad ad) {
}
#Override
public void onLoggingImpression(Ad ad) {
}
});
facebookAdView.loadAd();
}
private void showAdMobBanner() {
admobAdView = new com.google.android.gms.ads.AdView(this);
admobAdView.setAdSize(com.google.android.gms.ads.AdSize.SMART_BANNER);
admobAdView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
bannerView.addView(admobAdView);
admobAdView.loadAd(new AdRequest.Builder().build());
}
//Interstitial Ads
private void showFacebookInterstitial() {
facebookInterstitialAds = new InterstitialAd(this, "Interstitial_Ad_ID");
facebookInterstitialAds.setAdListener(new InterstitialAdListener() {
#Override
public void onInterstitialDisplayed(Ad ad) {
}
#Override
public void onInterstitialDismissed(Ad ad) {
//any work on ads close
finish();
}
#Override
public void onError(Ad ad, AdError adError) {
//if load fail then
loadAdMobInterstitial();
}
#Override
public void onAdLoaded(Ad ad) {
}
#Override
public void onAdClicked(Ad ad) {
}
#Override
public void onLoggingImpression(Ad ad) {
}
});
facebookInterstitialAds.loadAd();
}
private void loadAdMobInterstitial() {
adMobInterstitialAds = new com.google.android.gms.ads.InterstitialAd(this);
adMobInterstitialAds.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
adMobInterstitialAds.loadAd(new AdRequest.Builder().build());
adMobInterstitialAds.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
super.onAdClosed();
//any work on ads close
finish();
}
});
}
//Interstitial Ads show on button click listener
public void showAds(View view){
if (facebookInterstitialAds.isAdLoaded())
facebookInterstitialAds.show();
else if (adMobInterstitialAds!=null)
if (adMobInterstitialAds.isLoaded())
adMobInterstitialAds.show();
}
#Override
protected void onPause() {
super.onPause();
if (admobAdView != null)
admobAdView.pause();
}
#Override
protected void onResume() {
super.onResume();
if (admobAdView != null)
admobAdView.resume();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (facebookAdView != null)
facebookAdView.destroy();
if (admobAdView != null)
admobAdView.destroy();
if (facebookInterstitialAds != null)
facebookInterstitialAds.destroy();
}
}

Add Just two line in your onCreate
AdView ad = (AdView) findViewById(R.id.adView);
ad.loadAd(new AdRequest());
And add AddView in Your XML like
<com.google.ads.AdView
android:id="#+id/adView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
ads:adSize="SMART_BANNER"
ads:adUnitId="#string/ads_unit_id"
ads:loadAdsOnCreate="true" />

You can download complete source code from here
Add following lib in your dependency
compile 'com.google.android.gms:play-services-ads:7.8.0'
For Smart Banner
Add following things in xml file
<com.google.android.gms.ads.AdView
android:id="#+id/ad_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
ads:adSize="SMART_BANNER"
ads:adUnitId="#string/banner_ad_unit_id" />
Add following things in java file
mAdView = (AdView) findViewById(R.id.ad_view);
AdRequest adRequest = new AdRequest.Builder().build();
// Start loading the ad in the background.
mAdView.loadAd(adRequest);
For Interstitial Advertise
mInterstitialAd = new InterstitialAd(MainActivity.this);
mInterstitialAd.setAdUnitId(getResources().getString(R.string.full_screen_ad_unit_id));
AdRequest adRequestFull = new AdRequest.Builder().build();
mInterstitialAd.loadAd(adRequestFull);
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
// Full screen advertise will show only after loading complete
mInterstitialAd.show();
}
});

Related

Android AdMob banner ad not showing up

I am using the following view in my activity xml.
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
ads:adSize="BANNER"
ads:adUnitId="ca-app-pub-6844894412719021~8904567900">
</com.google.android.gms.ads.AdView>
Your adUnitId seems to be incorrect. Did you get it via email?
You should be using following app id (replace ~ with /)
ads:adUnitId="ca-app-pub-6844894412719021/8904567900">
Try to add to your xml:
xmlns:ads="http://schemas.android.com/apk/res-auto"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
and to gradle:
compile 'com.google.android.gms:play-services-ads:9.8.0'
It looks like you are using app_id instead of banner_id.
<string name="app_id">ca-app-pub-xxxxxxxxxxxxxxxx~xxxxxxxxxx</string>
<string name="banner_id">ca-app-pub-xxxxxxxxxxxxxxxx/xxxxxxxxxx</string>
these two values are different from each other.
Check if you have latest versions of adMob and GooglePlayServices lib.
When you try to show banner inside of svg images then care about it are you using smart banner or banner it may effect, sometimes you implement the code right but when you try to show toast in ad loaded like this.
adView2.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
Toast.makeText(App_Mainpage.this, "add is loaded", Toast.LENGTH_SHORT).show();
adView2.setVisibility(View.VISIBLE);
}
#Override
public void onAdFailedToLoad(int errorCode) {
}
#Override
public void onAdOpened() {
}
#Override
public void onAdLeftApplication() {
}
#Override
public void onAdClosed() {
}
});
AdRequest adRequest = new AdRequest.Builder().build();
adView2.loadAd(adRequest);
if it shows you in toast the ad is loaded but not showing when you testing, then actually you are implementing Smart_banner that takes large space to show, so use Banner Just it will show then, i solve it by change this thing.
then i changed to smart banner .

Failed to load ad 0 in native ad

I am using native Admob ad for android app but everytime i am getting
Failed to load ad : 0
when i used addTestDevice(deviceId) is working fine.
My Code:
private void refreshAd(boolean requestAppInstallAds, boolean requestContentAds, final LinearLayout mLayout) {
AdLoader adLoader = new AdLoader.Builder(mContext, Config.ADMOB_AD_UNIT_ID)
.forAppInstallAd(new NativeAppInstallAd.OnAppInstallAdLoadedListener() {
#Override
public void onAppInstallAdLoaded(NativeAppInstallAd appInstallAd) {
// Show the app install ad.
NativeAppInstallAdView adView = (NativeAppInstallAdView) ((AppCompatActivity) mContext).getLayoutInflater()
.inflate(R.layout.ad_app_install, null);
populateAppInstallAdView(appInstallAd, adView);
mLayout.removeAllViews();
mLayout.addView(adView);
}
})
.forContentAd(new NativeContentAd.OnContentAdLoadedListener() {
#Override
public void onContentAdLoaded(NativeContentAd contentAd) {
// Show the content ad.
}
})
.withAdListener(new AdListener() {
#Override
public void onAdFailedToLoad(int errorCode) {
// Handle the failure by logging, altering the UI, etc.
Log.d("Opennaukri","errorCode = "+errorCode);
}
})
.withNativeAdOptions(new NativeAdOptions.Builder()
// Methods in the NativeAdOptions.Builder class can be
// used here to specify individual options settings.
.build())
.build();
adLoader.loadAd(new AdRequest.Builder().build());
// .addTestDevice("E9990FA9258AD0601F492495AC3F15EB").build());
// // Check the LogCat to get your test device ID
// .addTestDevice("B7BEE8B7CDBAC269CBB598F9DB6C4769")
// Check the LogCat to get your test device ID
}
private void populateAppInstallAdView(NativeAppInstallAd nativeAppInstallAd,
NativeAppInstallAdView adView) {
adView.setHeadlineView(adView.findViewById(R.id.appinstall_headline));
// adView.setImageView(adView.findViewById(R.id.appinstall_image));
adView.setBodyView(adView.findViewById(R.id.appinstall_body));
adView.setCallToActionView(adView.findViewById(R.id.appinstall_call_to_action));
adView.setIconView(adView.findViewById(R.id.appinstall_app_icon));
adView.setPriceView(adView.findViewById(R.id.appinstall_price));
adView.setStarRatingView(adView.findViewById(R.id.appinstall_stars));
adView.setStoreView(adView.findViewById(R.id.appinstall_store));
// Some assets are guaranteed to be in every NativeAppInstallAd.
((TextView) adView.getHeadlineView()).setText(nativeAppInstallAd.getHeadline());
((TextView) adView.getBodyView()).setText(nativeAppInstallAd.getBody());
((TextView) adView.getCallToActionView()).setText(nativeAppInstallAd.getCallToAction());
((ImageView) adView.getIconView()).setImageDrawable(nativeAppInstallAd.getIcon()
.getDrawable());
// Some aren't guaranteed, however, and should be checked.
if (nativeAppInstallAd.getPrice() == null) {
adView.getPriceView().setVisibility(View.INVISIBLE);
} else {
adView.getPriceView().setVisibility(View.VISIBLE);
((TextView) adView.getPriceView()).setText(nativeAppInstallAd.getPrice());
}
if (nativeAppInstallAd.getStore() == null) {
adView.getStoreView().setVisibility(View.INVISIBLE);
} else {
adView.getStoreView().setVisibility(View.VISIBLE);
((TextView) adView.getStoreView()).setText(nativeAppInstallAd.getStore());
}
if (nativeAppInstallAd.getStarRating() == null) {
adView.getStarRatingView().setVisibility(View.INVISIBLE);
} else {
((RatingBar) adView.getStarRatingView())
.setRating(nativeAppInstallAd.getStarRating().floatValue());
adView.getStarRatingView().setVisibility(View.VISIBLE);
}
// Assign native ad object to the native view.
adView.setNativeAd(nativeAppInstallAd);
}
Steps to see ads in your app:
1) add internet permision in your manifest file
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
2) In the Gradle file insert this line within dependencies
compile 'com.google.android.gms:play-services-ads:7.5.0'
3) now we need to display the add so we add these few lines in the layout
anyLayout xmlns:android...
xmlns:ads = "http://schemas.android.com/apk/res-auto"
...
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:adSize="BANNER"
ads:adUnitId="ca-app-pub-xxxxxxxxxxxxxxx/xxxxxxxxx.">
</com.google.android.gms.ads.AdView>
4) finally we need to load the ad in the layout, which only requires 3 lines:
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
If you run the app from the emulator or you check in the layout editor (in android studio) you will see how you ad will look like. If everythings goes right in the layout editor you will see a white banner with "ads by google" (or something like that) and if you run the app in the emulator a dummy banner will show up.
Once you build the apk (signed or unsigned) and install it on a device you won't see any ad yet because google admob need some time between you register a new app to deliver ads and when the ads start to appear (<12h).
Hope this helps!
I had success with the following code:
private LinearLayout mAdContainer;
private NativeExpressAdView mAdmobAdView;
private AdRequest mAdmobAdRequest;
[...]
private void loadAds() {
// find out the width of the device in dp
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
float deviceWidthInDp = displayMetrics.widthPixels / displayMetrics.density;
int adWidth = (int)(deviceWidthInDp);
mAdContainer.removeAllViews();
mAdmobAdView = new NativeExpressAdView(this);
mAdmobAdView.setAdSize(new AdSize(adWidth, 250)); // AdSize(width, height), height ranges from 80 to 1200
mAdContainer.addView(mAdmobAdView);
mAdmobAdView.setAdUnitId(getString(R.string.admob_id)); // set your admob id
mAdmobAdRequest = new AdRequest.Builder()
.build();
mAdmobAdView.loadAd(mAdmobAdRequest);
}

How hide and show admob banner adview runtime

Hello guys I am using admob banner to show ads.
So I left some space at bottom so admob mob banner load.
So if user turn off internet then I want to use that banner space to show content of my activity. while if user turn on his internet again then I shrink my activity content and show admob banner again, So in short I want to grow or shrink layout space.
This is code I try. This code removes banner space if internet is off. but I dont know how to add banner again if user turn on internet.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(getApplicationContext(), "ca-app-pub-3940256099942544~3347511713");
final AdView mAdView = (AdView) findViewById(R.id.adView);
final AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdFailedToLoad(int i) {
//super.onAdFailedToLoad(i);
mAdView.setVisibility(View.GONE);
}
});
}
}
First you need to decide when your application will check connection again.
Check the lifecycle at https://developer.android.com/reference/android/app/Activity.html
After, lets suppose you want to check everytime the application back to the acitivty that you want to show your adview.
#Override
protected void onRestart() {
if(checkAppConnectionStatus(MainActivity.this)){mAdView.setVisibility(View.VISIBLE);}
else{ mAdView.setVisibility(View.GONE);}
super.onRestart();
}
public static boolean checkAppConnectionStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
return true;
}else{
return false;
}
}
Check my other answer to know more about how to use like in an utils class appConnectionStatus:
Internet Connection

Implementing native ads in android using Admob? is it possible?

I'm trying to implement native ads in my android application. But I want to do it using admob only. I searched a lot for solution but could not find exact one to do so.
I know it is possible using MoPub.
What I wanted to do is this:
Show ads inside list item which means one of the ListView/RecyclerView item can be one ad like below image.
I found some links and references but that doesn't explain proper implementation of the native ads.
Link 1 : Native ads overview
Link 2 : DFP Android Guides > Targeting
Link 3 : DFP Quick Start Guide
If it is not possible to do it using admob, MoPub is best solution for me right now.
Any help and guidance would be helpful. thanks.
Recently I stucked with the same question. Then I decided to post my solution for that to admobadapter. Hope it will help you.
The basic usage could look like:
ListView lvMessages;
AdmobAdapterWrapper adapterWrapper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initListViewItems();
}
/**
* Inits an adapter with items, wrapping your adapter with a {#link AdmobAdapterWrapper} and setting the listview to this wrapper
* FIRST OF ALL Please notice that the following code will work on a real devices but emulator!
*/
private void initListViewItems() {
lvMessages = (ListView) findViewById(R.id.lvMessages);
//creating your adapter, it could be a custom adapter as well
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
adapterWrapper = new AdmobAdapterWrapper(this);
adapterWrapper.setAdapter(adapter); //wrapping your adapter with a AdmobAdapterWrapper.
//here you can use the following string to set your custom layouts for a different types of native ads
//adapterWrapper.setInstallAdsLayoutId(R.layout.your_installad_layout);
//adapterWrapper.setcontentAdsLayoutId(R.layout.your_installad_layout);
//Sets the max count of ad blocks per dataset, by default it equals to 3 (according to the Admob's policies and rules)
adapterWrapper.setLimitOfAds(3);
//Sets the number of your data items between ad blocks, by default it equals to 10.
//You should set it according to the Admob's policies and rules which says not to
//display more than one ad block at the visible part of the screen,
// so you should choose this parameter carefully and according to your item's height and screen resolution of a target devices
adapterWrapper.setNoOfDataBetweenAds(10);
//It's a test admob ID. Please replace it with a real one only when you will be ready to deploy your product to the Release!
//Otherwise your Admob account could be banned
//String admobUnitId = getResources().getString(R.string.banner_admob_unit_id);
//adapterWrapper.setAdmobReleaseUnitId(admobUnitId);
lvMessages.setAdapter(adapterWrapper); // setting an AdmobAdapterWrapper to a ListView
//preparing the collection of data
final String sItem = "item #";
ArrayList<String> lst = new ArrayList<String>(100);
for(int i=1;i<=100;i++)
lst.add(sItem.concat(Integer.toString(i)));
//adding a collection of data to your adapter and rising the data set changed event
adapter.addAll(lst);
adapter.notifyDataSetChanged();
}
And the result will look like the following
Try using some other ad networking where it provides different types of native ads. Developers can customize the ads where to place and use it. For eg: if you need to place ads at second cell every 15 row, you can use like this.
Avocarrot provides that.
AvocarrotInstream myAd = new AvocarrotInstream(<yourListAdapter>);
myAd.initWithKey( "<your API Key>" );
myAd.setSandbox(true);
myAd.setLogger(true ,"ALL");
// Populate with In-Stream ads
myAd.loadAdForPlacement(this, "<your Placement Name>" );
// Bind the adapter to your list view component
<yourListView>.setAdapter(myAd);// here you are integrating ads to listview
myAd.setFrequency(2,15); // every 15 cells starting from the 2nd cell.
Here is Documentation it provides List ads and Feed ads.
Native ads are included in Google Play Services along with the rest of DFP/AdMob advertising. Make sure you have the following listed as dependencies in your build.gradle (note that 7.5.0 is the highest version as of this posting).
compile "com.google.android.gms:play-services-base:7.5.0"
compile "com.google.android.gms:play-services-ads:7.5.0"
Then you can display native ads
AdLoader adLoader = new AdLoader.Builder(context, "/6499/example/native")
.forAppInstallAd(new OnAppInstallAdLoadedListener() {
#Override
public void onAppInstallAdLoaded(NativeAppInstallAd appInstallAd) {
// Show the app install ad.
}
})
.forContentAd(new OnContentAdLoadedListener() {
#Override
public void onContentAdLoaded(NativeContentAd contentAd) {
// Show the content ad.
}
})
.withAdListener(new AdListener() {
#Override
public void onAdFailedToLoad(int errorCode) {
// Handle the failure by logging, altering the UI, etc.
}
})
.withNativeAdOptions(new NativeAdOptions.Builder()
// Methods in the NativeAdOptions.Builder class can be
// used here to specify individual options settings.
.build())
.build();
Click here for complete documentation.
As an addition to this thread, you can now implement NativeAds for Admob very easily by following the guide provided by Google using NativeExpressAdView .
For more information, check the google documentation :
https://firebase.google.com/docs/admob/android/native-express?hl=en
Add this code to your Listview Adapter
builder.forAppInstallAd(new NativeAppInstallAd.OnAppInstallAdLoadedListener() {
#Override
public void onAppInstallAdLoaded(NativeAppInstallAd ad) {
FrameLayout frameLayout =
(FrameLayout) findViewById(R.id.fl_adplaceholder);
NativeAppInstallAdView adView = (NativeAppInstallAdView) getLayoutInflater()
.inflate(R.layout.ad_app_install, null);
populateAppInstallAdView(ad, adView);
frameLayout.removeAllViews();
frameLayout.addView(adView);
}
});
AdLoader adLoader = builder.withAdListener(new AdListener() {
#Override
public void onAdFailedToLoad(int errorCode) {
Toast.makeText(MainActivity.this, "Failed to load native ad: "
+ errorCode, Toast.LENGTH_SHORT).show();
}
}).build();
adLoader.loadAd(new AdRequest.Builder().build());
Make some changes for listview Adapter and you will get populateAppInstallAdView() method from below link
Everything is covered in this example please go through this
https://github.com/googleads/googleads-mobile-android-examples/tree/master/admob
Adding to the mix, Tooleap Ads SDK provides a simple way to implement Admob's native ads.
Instead of requiring you to use the traditional listView adapter and showing the ad inside you content, they are showing admob native ads as a small floating bubble. When pressing on it you can see the full native ad.
Here is an example of using their SDK inside your activity class:
BubbleImageAd = new BubbleImageAd(this);
bubbleImageAd.setAdUnitId("YOUR_AD_UNIT_ID");
bubbleImageAd.loadAndShowAd(this);
You can check them out here.
This is working for me:
Copy Native template in project library.
in Build.gradle(Module:Appname) - add this:
implementation project(':nativetemplates')
implementation 'com.google.android.gms:play-services-ads:20.4.0'
in Setting.gradle(Appname) - add this:
include ':nativetemplates'
in Mainfest - update as earlier.
Before Application:
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"/>
add this Permission:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
In Layout file add this:
<com.google.android.ads.nativetemplates.TemplateView
android:id="#+id/my_template"
app:gnt_template_type="#layout/gnt_medium_template_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</com.google.android.ads.nativetemplates.TemplateView>
In program file:
MobileAds.initialize(this)
//build ad
val adLoader = AdLoader.Builder(this,"ca-app-pub-3940256099942544/2247696110")
.forNativeAd {
val style = NativeTemplateStyle.Builder().withMainBackgroundColor(ColorDrawable(Color.WHITE))
.build()
val template = findViewById<TemplateView>(R.id.my_template)
template.setStyles(style)
template.setNativeAd(it)
}.build()
//show ad
adLoader.loadAd(AdRequest.Builder().build())
If still not loading, Check with your admod credentials.
Well, this thread is probably outdated. But starting May 2015, and as of now, AdMob does support native ads (still in beta though).
https://support.google.com/admob/answer/6239795
Also it's available only to a limited number of developers as of its beta stage.
Admob in your android these are the codes needed.
<com.google.android.gms.ads.AdView
android:layout_alignParentBottom="true"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
ads:adSize="SMART_BANNER"
ads:adUnitId="ca-app-pub-4549020480017205/6066702579"
/>
//In your java class file
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
⟩⟩ In project structure, navigate to activity_main.xml and paste the following code in your layout.
<com.google.android.gms.ads.NativeExpressAdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:adSize="320x300"
ads:adUnitId="#string/ad_unit_id">
</com.google.android.gms.ads.NativeExpressAdView>
and in the same file i.e activity_main.xml add below lines of code in the header part
xmlns:ads="http://schemas.android.com/apk/res-auto"
⟩⟩ Now open MainActivity.java and add below lines of code in public class
private static String LOG_TAG = "EXAMPLE";
NativeExpressAdView mAdView;
VideoController mVideoController;
⟩⟩ Then under MainActivity.java and add below lines of code in onCreate() method.
// Locate the NativeExpressAdView.
mAdView = (NativeExpressAdView) findViewById(R.id.adView);
// Set its video options.
mAdView.setVideoOptions(new VideoOptions.Builder()
.setStartMuted(true)
.build());
// The VideoController can be used to get lifecycle events and info about an ad's video
// asset. One will always be returned by getVideoController, even if the ad has no video
// asset.
mVideoController = mAdView.getVideoController();
mVideoController.setVideoLifecycleCallbacks(new VideoController.VideoLifecycleCallbacks() {
#Override
public void onVideoEnd() {
Log.d(LOG_TAG, "Video playback is finished.");
super.onVideoEnd();
}
});
// Set an AdListener for the AdView, so the Activity can take action when an ad has finished
// loading.
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
if (mVideoController.hasVideoContent()) {
Log.d(LOG_TAG, "Received an ad that contains a video asset.");
} else {
Log.d(LOG_TAG, "Received an ad that does not contain a video asset.");
}
}
});
mAdView.loadAd(new AdRequest.Builder().build());
⟩⟩ Now open string.xml file in values folder and paste the below line of code.
<string name="ad_unit_id">ca-app-pub-39402560999xxxxx/21772xxxxx</string>
⟩⟩ Then open the Manifest file and add Internet permission to it.
<uses-permission android:name="android.permission.INTERNET" />
THE RESOURCE : How to insert AdMob Native Ad in your Android App
It is restricted to selected publishers at the moment. You'll need to contact a Google account manager in your region for implementation.
Yes it is possible you can use below code in xml file
<com.google.android.gms.ads.NativeExpressAdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:adSize="320x300"
ads:adUnitId="#string/ad_unit_id">
mAdView.setVideoOptions(new VideoOptions.Builder()
.setStartMuted(true)
.build());
mVideoController = mAdView.getVideoController();
mVideoController.setVideoLifecycleCallbacks(new VideoController.VideoLifecycleCallbacks() {
#Override
public void onVideoEnd() {
Log.d(LOG_TAG, "Video playback is finished.");
super.onVideoEnd();
}
});
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
if (mVideoController.hasVideoContent()) {
Log.d(LOG_TAG, "Received an ad that contains a video asset.");
} else {
Log.d(LOG_TAG, "Received an ad that does not contain a video asset.");
}
}
});
mAdView.loadAd(new AdRequest.Builder().build());
To add Native Templates in our app we have to follow some basic steps:
1-First, we have to download the Native Templates, so got to developers.google
2-Then click on the Download Native Templates, now you will be directed to Github
3-Then download the zip file from GitHub and extract the zip file to any folder and remember the location of the folder, we will use it later
4-Now go inside Android studio and click on File->New->Import Module, Now you will see a new window (Import-Module from Source) Now click on the Browse icon and select the nativetemplates folder and click on finish and wait for Gradle build to finish.
5-Now open the Gradle Scripts->build.gradle (Module: app) section and import the nativetemplates project and click the "sync Now" show at the top as shown below:
//adding native templates
implementation project(':nativetemplates')
https://www.studytonight.com/post/how-to-add-admob-native-ad-in-android-app#

AdMob won't show the banner until refresh or sign in to google plus

I've got a problem. My AdMob has been set up for some time now without any problem, but I noticed something wrong. Ad gets successfully loaded (i see message from ddms), but it won't show. It will get shown after periodical 60 seconds refresh or when I open up login to google plus. The problem happens only with Google Play Services AdMob and not with AdMobSDK jar. I'd switch to AdMob jar, however I'm using Google Play Game Services for leaderboards and achievements.
I suspect the problem is with view not being shown, or inproper settings.
So again, ad will show itself after 60 seconds (along with ad refresh) of waiting, or when I fire up the log in screen for google play services.
I'm adding my code, also I should mention that I've switched to new AdMob website and I repeat, that problem is not happening if I use AdMob jar file (the ad is then shown in 2-3 seconds like normal). I've cut the google play game services code (they don't affect this issue because i've tried in my other app without them, and the problem is still there).
MainActivity code:
public class MainActivity extends AndroidApplication {
public static enum AdsStatus {
SHOW_ADS, HIDE_ADS;
}
protected RelativeLayout layout;
protected static AdView adMobView;
public static class InnerHandler extends Handler {
WeakReference<MainActivity> mActivity;
InnerHandler(MainActivityactivity) {
mActivity = new WeakReference<MainActivity>(activity);
}
#Override
public void handleMessage(final Message msg) {
if(msg.obj instanceof AdsStatus) {
switch((AdsStatus)msg.obj) {
case SHOW_ADS:
mActivity.get().showAds();
break;
case HIDE_ADS:
mActivity.get().hideAds();
break;
}
}
}
}
protected Handler handler = new InnerHandler(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the layout
layout = new RelativeLayout(this);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libgdx View
View gameView = initializeForView(new MainApplicationListener(), true);
layout.addView(gameView);
//Ad Mob
final DisplayMetrics displayMetrics = MainActivity.this
.getApplicationContext().getResources()
.getDisplayMetrics();
if (displayMetrics.widthPixels >= 800 && displayMetrics.heightPixels >= 480) {
if(adMobView != null) {
adMobView.destroy();
}
adMobView = new AdView(AirDance.this);
adMobView.setAdUnitId(<MY_ID_IS_HERE>);
adMobView.setAdSize(AdSize.SMART_BANNER);
RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
adParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(<MY_DEVICE_IS_HERE>)
.build();
adMobView.loadAd(adRequest);
layout.addView(adMobView, adParams);
}
// Hook it all up
setContentView(layout);
}
#Override
protected void onResume() {
super.onResume();
AppRater.applicationLaunched(this, analytics);
if(adMobView != null) {
adMobView.resume();
}
}
#Override
protected void onPause() {
super.onPause();
if(adMobView != null) {
adMobView.pause();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if(adMobView != null) {
adMobView.destroy();
adMobView = null;
}
}
public void showAds() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(adMobView != null) {
adMobView.setEnabled(true);
adMobView.setVisibility(View.VISIBLE);
}
}
});
}
public void hideAds() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(adMobView != null) {
adMobView.setEnabled(false);
adMobView.setVisibility(View.GONE);
}
}
});
}
}
And here is AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="..."
android:installLocation="auto"
android:versionCode="16"
android:versionName="1.2.6" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-feature android:name="android.hardware.screen.landscape"/>
<uses-feature android:name="android.hardware.touchscreen.multitouch" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="MainActivity">
<meta-data android:name="com.google.android.gms.games.APP_ID"
android:value="#string/app_id" />
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name="...MainActivity"
android:label="MainActivity"
android:screenOrientation="landscape">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- adMob -->
<activity android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
</application>
</manifest>
EDIT :
okay, so ad gets visible after I lock and unlock screen with app open, also you can click on invisible ad
EDIT :
Okay I think I solved it. I just manually reload whole layout onAdLoad event. Anyway, this is just functional solution, it does not explain why it happens with Google Play
Services AdMob.
adMobView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
layout.requestLayout();
}
});
}
});
As nobody has replied with explanation, I'm going to consider this one solved. I just manually reload whole layout onAdLoad event. Anyway, this is just functional solution, it does not explain why it happens with Google Play Services AdMob.
adMobView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
layout.requestLayout();
}
});
}
});
Also, as mentioned by user3263204, you can try this
adMobView.setBackgroundColor(Color.BLACK);
to solve your problem.
The above solution works. Even a simpler way to keep the banner shown is to set its background.
adMobView.setBackgroundColor(Color.BLACK);
As user3263204 says, you can use setBackgroundColor to make the adview appear.
You can make the background transparent, if (as in my case) you have the adview over something else:
adMobView.setBackgroundColor(getResources().getColor(android.R.color.transparent));
You can also requestWindowFeature(Window.FEATURE_NO_TITLE); and set to full screen and the ads shows.
banner.setBackgroundColor(Color.TRANSPARENT);
This seems to fix the issue for me. Also be sure to run the banner creation code from within the UI thread.
activity.runOnUiThread(new Runnable()
{
#Override
public void run()
{
// all your banner creation code is here
banner.setBackgroundColor(Color.TRANSPARENT);
}
});

Categories

Resources