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());
Related
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.
When admob code is initialized in a Phonegap/Cordova app that makes use of localStorage, the localStorage seems to get overridden by the admob ad view.
Here's the code for initialization of the admob code (using v6.2.1 of the SDK) in a Cordova 2.2 app::
public class Foo extends DroidGap
{
private AdView adView;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.setIntegerProperty("splashscreen", R.drawable.splash);
super.loadUrl("file:///android_asset/www/index.html", 3000);
adView = new AdView(this, AdSize.SMART_BANNER, "AD_MOB_ID");
root.addView(adView);
AdRequest request = new AdRequest();
request.setTesting(true);
adView.loadAd(request);
}
The ad gets loaded but the localStorage which I use to maintain the session of the user seems to get cleared and the login page is displayed. When I comment the admob initialization code, the localStorage gets reverted and the user's session is back.
As per the instructions on [1] and [2], I have added a handler::
public class Foo extends DroidGap
{
private AdView adView;
private Handler mHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.setIntegerProperty("splashscreen", R.drawable.splash);
super.loadUrl("file:///android_asset/www/index.html", 3000);
mHandler.postDelayed(new Runnable() {
public void run() {
loadAdmob();
}
}
}
private void loadAdmob()
{
adView = new AdView(this, AdSize.SMART_BANNER, "AD_MOB_ID");
root.addView(adView);
AdRequest request = new AdRequest();
request.setTesting(true);
adView.loadAd(request);
}
This tries loading the ads 10 seconds later but I get the following message in logcat::
adRequestUrlHtml: <html>...
Received ad url: <url: ...
Request Scenario: Offline with no buffered ads.
Network is unavailable. Aborting ad request.
onFailedToReceiveAd(A network error occurred.)
I can confirm that there is no problem with the network connection (because the rest of the data in the app gets displayed and is fetched over the network) and yet the ad does not display. Am I doing something wrong or is this a bug? A workaround for this problem will be helpful.
[1] Android + HTML5(LocalStorage) + Admob: Bug?
[2] https://github.com/phonegap/phonegap/wiki/In-App-Advertisements
I experienced the same problem with receiving the network error when introducing the delay (perhaps due to running on another thread, it loses the necessary permissions to query the network.)
The way I solved this was to override onAttachToWindow() and invoke the adMob initialization from in there, and removing the handler code altogether. It has the side effect of being near instant with no delay as well.
#Override public void onAttachedToWindow() {
super.onAttachedToWindow();
doAdMob();
};
private void doAdMob() {
adView = new AdView(this, AdSize.BANNER, "ID");
LinearLayout layout = super.root;
layout.addView(adView);
AdRequest request = new AdRequest();
request.addTestDevice("ID");
adView.loadAd(request);
}
I'm using Cordova 2.5 btw.
UPDATE: AdMod still corrupts the localstorage, but it's loaded by the time AdMob has a chance to wipe it out. However, on a subsequent reload, it will be reset. I've since resolved this behavior by adding
window.setTimeout(saveSettings, 5000);
after I've loaded my localStorage settings. This is highly hackish of course.. but seems to do the trick so far. Also note, I've only been using the test ads for AdMob.
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);