How to stop Banner Ad loading? - android

Some user intentionally try to click banner ads many times.Due to this we face problem of account suspension or termination. Does anyone know how to stop the ad being loading if it cross some limit(for example 3).
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.setRequestAgent("android_studio:ad_template").build();
adView.loadAd(adRequest);
if(currentbannerclick>3)
{
// some code to not load the ad.
}

LinearLayout id=container
AdView id=adView
if(currentbannerclick>3)
container.removeView(adView);
Thank you everyone for your answer.

You can identify if Ad is clicked using Activity life-cycle callbacks. you can then find out how much time user clicked your Ad and call adView.loadAd(adRequest); only if the user clicked your Ad less than your threshold.

You can attach an AdListener to your AdView and increase your click counter in the onAdLoaded or onAdOpened methods. More info here: https://developers.google.com/android/reference/com/google/android/gms/ads/AdListener#public-methods

This should work:
private void loadAd() {
// This is a one element array because it needs to be declared final
// TODO: you should probably load the default value from somewhere because of activity restarts
final int[] currentBannerClick = {0};
final AdView adView = (AdView) findViewById(R.id.adView);
adView.setAdListener(new AdListener() {
#Override
public void onAdOpened() {
super.onAdOpened();
currentBannerClick[0]++;
if (currentBannerClick[0] > 3) {
adView.setVisibility(View.INVISIBLE);
adView.destroy();
}
// TODO: save currentBannerClick[0] somewhere, see previous TODO comment
}
});
if (currentBannerClick[0] <= 3) {
AdRequest adRequest = new AdRequest.Builder().addTestDevice(YOUR_DEVICE_ID).build();
adView.setVisibility(View.VISIBLE);
adView.loadAd(adRequest);
} else {
adView.setVisibility(View.INVISIBLE);
}
}

You can also limit number of Ads displayed for user in AdMob System. You can set limit of 3 ads per user per minut, hour or day.

Related

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);
}

Reduce android app startup time

I am developing an app that uses a shared preferences file and it also contains ads. When I open my app for the first time (running from android studio) my main activity's taking 14-16 seconds to load. After caching it takes 2 seconds to load. I realised that I was putting too many operations in my onCreate() method.Then I tried using onResume(), but it is still taking the same time. I would like to know how I could reduce this startup time. My app uses a shared preference file and it contains ads.I also noticed that my app cache is 20MB.
Code is as follows
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
EditText nme_key = (EditText)findViewById(R.id.name_key);
EditText cls_key = (EditText)findViewById(R.id.class_key);
EditText num_key = (EditText)findViewById(R.id.number_key);
SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.preference_file_key),MODE_PRIVATE);
nme_key.setText(sharedPreferences.getString("name","name"));
cls_key.setText(sharedPreferences.getString("class","class"));
num_key.setText(sharedPreferences.getString("number","number"));
MobileAds.initialize(getApplicationContext(), "");
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().addTestDevice("").build();
mAdView.loadAd(adRequest);
}
I have 3 questions
How to reduce the startup time of my app ( Threads?)
How to reduce the cache size of my app
How can I improve my app performance
I found out that Ads are the reason that makes my application takes too long to start.
So, this how I fixed it:
//run in the background
AsyncTask.execute(() -> {
MobileAds.initialize(this, initializationStatus -> {});
//Banner Ad
AdView adView = findViewById(R.id.ad_view);
AdRequest adRequest = new AdRequest.Builder().build();
//Interstitial Ad
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
//you have to load the Ads in the foreground
this.runOnUiThread(() -> {
adView.loadAd(adRequest);
mInterstitialAd.loadAd(new AdRequest.Builder().build());
});
});
How to show Interstitial Ad:
button.setOnClickListener(view -> {
//check first, if it is instantiated and loaded
if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
});
But be aware that this will make your app start without showing any ads until they load up.
I know I'm very late but I hope this will help people in the feature.

AdMob interstitial doesn't show on Android

I have an Android app and I'm trying to add AdMob interstitials into it. I create them this way
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId(getResources().getString(R.string.ad));
interstitial.loadAd(AdUtils.createRequest());
and when the moment is appropriate, I show them like this:
if(interstitial.isLoaded()) {
interstitial.show();
}
When I test this code on the emulator, everything is fine. But when I run it on the real device, it often (about a half of all shows) displays only a black screen with the close button and no advertisement image at all. Is there any solution to this issue?
You can try as below.
Declare this as a variable.
private InterstitialAd interstitial;
then use this part in your onCreate method
interstitial = new InterstitialAd(this, "your id");
// Create ad request
AdRequest adRequest = new AdRequest();
// Begin loading your interstitial
interstitial.loadAd(adRequest);
// Set Ad Listener to use the callbacks below
interstitial.setAdListener(this);
and at last set this outside your onCreate method so basically set below code in your activity..
#Override
public void onReceiveAd(Ad ad) {
// TODO Auto-generated method stub
if (ad == interstitial) {
interstitial.show();
}
}
Hope this will help you.

Admob closes app after closing ad?

I have one Activity in my app. Now I wanted to add an Admob interstitial banner. Unfortunately the old activity is also closed when the user closes the ad.
I added something like this:
interstitial = new InterstitialAd(this, "*************");
// Create ad request
AdRequest adRequest = new AdRequest();
// and begin loading your interstitial
interstitial.loadAd(adRequest);
interstitial.setAdListener(this);
And started the ad by using
if (interstitial.isReady()){
interstitial.show();
}
The representation of the app is working fine.
What can I do to solve the problem?
There is an attribute in your AndroidManifest.xml file, like android:noHistory="true" You must delete this. it solves the problem
Do like this
private boolean isAddShown = false;
make this isAddShown = true when the add is visible
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if(!isAddShown){
super.onBackPressed();
}else{
isAddShown = false;
}
}

admob : changing ads

I use following code to show ads in onCreate() of the activity
Since my activity is displayed for longer times, can I refresh the ads ? or will it automatically refresh them ? Do I even need to change them or should not bother it ?
//only ask for test ad, in emulator , should remove this later in real device
AdRequest adRequest = new AdRequest();
//adRequest.addTestDevice(AdRequest.TEST_EMULATOR); // Emulator
//adRequest.addTestDevice("TEST_DEVICE_ID");
// Create the adView
adView = new AdView(this, AdSize.BANNER, "908908098098");
// Lookup your LinearLayout assuming it’s been given
// the attribute android:id="#+id/mainLayout"
LinearLayout layout = (LinearLayout)findViewById(R.id.adLayout);
// Add the adView to it
layout.addView(adView);
// Initiate a generic request to load it with an ad
adView.loadAd(adRequest);
Change app settings in admob account:
Also you should remove test mode before publishing:
AdView adView = (AdView) findViewById(R.id.ad);
AdRequest adRequest = new AdRequest();
adView.loadAd(adRequest);
In onDestroy(): adView.destroy();
In layout:
<com.google.ads.AdView
android:id="#+id/ad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
ads:adSize="BANNER"
ads:adUnitId="#string/admob_publisher_id"
ads:loadAdOnCreate="true" >
</com.google.ads.AdView>
In AdMob app settings select this: Disable test mode for all requests
Admob ads are refreshed at a rate set up on your admob account. Go to your account, click on "Manage Settings", then "App Settings", and look for the auto refresh parameters there.
declare adView in activity as data member , then create Timer Task as bellow in your constructor of the activity
adView = (AdView) findViewById(R.id.adView);
TimerTask tt = new TimerTask() {
#Override
public void run() {
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
adView.loadAd(new AdRequest());
}
});
}
};
Timer t = new Timer();
t.scheduleAtFixedRate(tt, 0, 1000 * 60);

Categories

Resources