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.
Related
I am trying to put an interstitial ad after every 5 games the user plays. What I've done is created an empty object with the following script:
using UnityEngine;
using GoogleMobileAds.Api;
public class AdBetweenGames : MonoBehaviour {
InterstitialAd interstitial;
void Start()
{
if(PlayerPrefs.GetInt("games-played", -1) % 5 == 0)
{
this.ShowInterstitial();
}
}
private void RequestInterstitial()
{
string adUnitId = "UNITID";
// Initialize an InterstitialAd.
interstitial = new InterstitialAd(adUnitId);
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the interstitial with the request.
interstitial.LoadAd(request);
}
public void ShowInterstitial()
{
RequestInterstitial();
Debug.Log("Interstatial ad called.");
if (interstitial.IsLoaded())
{
interstitial.Show();
}
}
}
I am sure the code here is called properly based on the debug log. I've also tried doing banner ads and they show without a problem after 1-2 seconds. I am making an android game.
Also I was thinking, could it be that the ad needs some extra time to load and I am clicking try again too early. But then what would a solution be?
The interstitial ad of ad mob need time to load try it in update and wait for at least 4 sec and call ShowInterstitial function inside a bool set its value true in start and false it after calling the function to show ad once.
I'm having issues with ADs in my Android App.
Sometimes the AD is not shown, probably depending on the DPI or Size of the screen's device.
In my code, I implemented a check to set View.GONE in case the AD fails to load, but despite that on some devices I still have blank spaces where it's supposed to be the AD
For example, here one of my ADs
if(holder.nativeExpressAdView != null) {
AdRequest request = new AdRequest.Builder()
.build();
holder.nativeExpressAdView.loadAd(request);
Utilities.setAdListenerNative(holder.nativeExpressAdView);
}
//ADs listener to remove view if it fails load
//NATIVE ADS
public static void setAdListenerNative(final NativeExpressAdView nativeExpressAdView) {
nativeExpressAdView.setAdListener(new AdListener() {
#Override
public void onAdFailedToLoad(int i) {
super.onAdFailedToLoad(i);
nativeExpressAdView.setVisibility(View.GONE);
}
});
}
First show me your log
Second Dont use "Gone" because this will change the position of the adView if you are using other sizes of Android scale you will see that.
Third use a debugger.
Use "invisible"
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 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.
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.