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);
Related
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);
}
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.
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.
I've just created an account on AdMobs, created banner for test.
The code is from BannerExample, without addTestDevice(...)
public class MyActivity extends ActionBarActivity {
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
// Gets the ad view defined in layout/ad_fragment.xml with ad unit ID set in
// values/strings.xml.
mAdView = (AdView) findViewById(R.id.ad_view);
// Create an ad request. Check logcat output for the hashed device ID to
// get test ads on a physical device. e.g.
// "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device."
AdRequest adRequest = new AdRequest.Builder()
.build();
// Start loading the ad in the background.
mAdView.loadAd(adRequest);
}
activity_my.xml
<com.google.android.gms.ads.AdView
android:id="#+id/ad_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:adSize="BANNER"
ads:adUnitId="ca-app-pub-6784520601040456/7994286128" />
But I see only Test banner, when I launch the application.
Should I specify something else, to see the real banner?
Try to check it out in real device. Add usually doesnt show in emulator.
I have created a application with webview for displaying for AdMob. I am using the following code.
private AdView adView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout layout = (LinearLayout) findViewById(R.id.linearlayout1);
adView = new AdView(this, AdSize.BANNER, "/6253334/dfp_example_ad");
View view = addHome(this,"https://www.google.co.in/");
layout.addView(view,new LinearLayout.LayoutParams(200, 100));
final AdRequest adRequest = new AdRequest();
adRequest.addTestDevice("1CD0A829B8C49C9F7590DD3B4C5EC553");
adRequest.setTesting(true);
setContentView(layout);
new Thread(){
public void run() {
Looper.prepare();
adView.loadAd(adRequest);
};
}.start();
}
I am always getting onFailedToReceiveAd(A network error occurred) error, instead of getting the ads.
Have you added your INTERNET Permission to your Manifest file and made sure the device actually has Internet access?
<uses-permission android:name="android.permission.INTERNET" />
Are other applications on your phone able to access the Internet? What I mean is have you tested if other apps are able to access the internet? Maybe this is not an issue of your application, but of the phone in general being unable to access the internet for whatever reason.
Furthermore, what I see in your above code:
You are calling "layout = findViewById(...)" before even calling "setContentView(...)". This should actually result in a Nullpointer Exception when calling layout.addView().
You could also try this code (inside your onCreate() method):
setContentView(R.layout.yourlayout);
AdView ad = new AdView(this, AdSize.SMART_BANNER, "yourid");
LinearLayout ll = (LinearLayout) findViewById(R.id.linearlayout1);
if (ll != null) {
ll.addView(ad);
}
ad.loadAd(new AdRequest());