Admob: Adding multiple Test Devices (ID) - android

I am using admob to display ads in my android app. I can add single Test Device using addTestDevice("DEVICE_ID")
But how to add multiple devices as Test Devices?
I tried addTestDevice("DEVICE_ID_1, DEVICE_ID_2, DEVICE_ID_3") but its not working.

Call addTestDevice for each device_id.
Builder adRequestBuilder = new AdRequest.Builder();
adRequestBuilder.addTestDevice(DEVICE_ID_1);
adRequestBuilder.addTestDevice(DEVICE_ID_2);
adRequestBuilder.addTestDevice(DEVICE_ID_3);
...
AdRequest adRequest = adRequestBuilder.build();
You can call this method multiple times before build it.

From the google api docs:
AdRequest request = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR) // All emulators
.addTestDevice("AC98C820A50B4AD8A2106EDE96FB87D4") // My Galaxy Nexus test phone
.build();
So you can add an unlimited number of devices in the same request by just calling addTestDevice again.
Or you can do it in the xml like the comment of karan mer suggested.

Add this way and to get device id check this post
.addTestDevice("DEVICE_ID_1")
.addTestDevice("DEVICE_ID_2")
.addTestDevice("DEVICE_ID_3")

Related

Should we first call MobileAds.setRequestConfiguration or MobileAds.initialize?

There isn't much documentation on this. I was wondering, should we first call
RequestConfiguration conf= new RequestConfiguration.Builder()
.setMaxAdContentRating(
MAX_AD_CONTENT_RATING_T)
.build();
MobileAds.setRequestConfiguration(conf);
MobileAds.initialize(context, APP_ID);
Or
MobileAds.initialize(context, APP_ID);
RequestConfiguration conf= new RequestConfiguration.Builder()
.setMaxAdContentRating(
MAX_AD_CONTENT_RATING_T)
.build();
MobileAds.setRequestConfiguration(conf);
In https://developers.google.com/admob/android/quick-start
Although Google recommend calling MobileAds.initialize as early as possible
Before loading ads, have your app initialize the Mobile Ads SDK by
calling MobileAds.initialize() which initializes the SDK and calls
back a completion listener once initialization is complete (or after a
30-second timeout). This needs to be done only once, ideally at app
launch.
They also mention "request-specific flags" need to be set before MobileAds.initialize.
Warning: Ads may be preloaded by the Mobile Ads SDK or mediation
partner SDKs upon calling MobileAds.initialize(). If you need to
obtain consent from users in the European Economic Area (EEA), set any
request-specific flags (such as tagForChildDirectedTreatment or
tag_for_under_age_of_consent), or otherwise take action before loading
ads, ensure you do so before initializing the Mobile Ads SDK.
So, not super clear on which should be called first.
According to Google Developer support, the following is the right way to do
https://groups.google.com/forum/#!category-topic/google-admob-ads-sdk/android/17oVu0sABjs
RequestConfiguration conf= new RequestConfiguration.Builder()
.setMaxAdContentRating(
MAX_AD_CONTENT_RATING_T)
.build();
MobileAds.setRequestConfiguration(conf);
MobileAds.initialize(context, APP_ID);
It's done as such:
MobileAds.RequestConfiguration =
new RequestConfiguration
.Builder()
.SetTagForChildDirectedTreatment(RequestConfiguration.TagForChildDirectedTreatmentTrue)
.SetMaxAdContentRating(RequestConfiguration.MaxAdContentRatingG)
#if DEBUG
.SetTestDeviceIds(new[] { "..." })
#endif
.Build();
according to the official documentation
Before loading ads, have your app initialize the Mobile Ads SDK by calling MobileAds.initialize() which initializes the SDK and calls back a completion listener once initialization is complete (or after a 30-second timeout). This needs to be done only once, ideally at app launch.
So , you should initialize MobileAds first ,look at the example here form the official documentation :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}

High ram usage with admob

I am trying to place ads inside my app. According to Admob Documentation I have to initialize Mobile Ads SDK
MobileAds.initialize(this, "YOUR_ADMOB_APP_ID");
This causes spike in high ram usage in code.
But if i remove this line then ram usage drops & and this line of code doesn't seem to have any affect on servering ads inside the app.
Also when requesting ad from admob ram usage again spike up and causes 3-4 GC events on app startup. I believe this is memory leak.
Here's how i am requesting ad in onCreate method
AdRequest request = null;
if (BuildConfig.DEBUG) {
//Facebook Audience Network
List<String> testDeviceId = new ArrayList<>();
testDeviceId.add("TESTID");//Redmi Note 3
testDeviceId.add("TESTID");//Moto G 1st Gen
AdSettings.addTestDevices(testDeviceId);
//Google Ad-mob
request = new AdRequest.Builder()
.addTestDevice("TESTID")//Redmi Note 3
.addTestDevice("TESTID")//Mot G 1st Gen
.build();
} else {
request = new AdRequest.Builder()
.build();
}
AdView mAdView = findViewById(R.id.adView);
mAdView.loadAd(request);
When loading this banner ads several GC event are kicked in. If i don't load ads GC event are never kicked in.
Is this behavior normal with admob? How can i resolve this?
Google AdView has WebView with a lot of animation inside. It will heats up all mobile CPU.
AdView take 30% of CPU.
Solution : You can also add custom listeners to destroy after some time and recreate in order to handle it even better. Serverside there is also a parameter telling the app ad how soon should ask for a new ad, I am not sure if it exist in all cases but it is there for DFP accounts.
here is the easiest way i would suggest
new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
if (!isBeingDestroyed) {
final AdRequest adRequest = new AdRequest();
final AdView adView = (AdView) findViewById(R.id.ad);
adView.loadAd(adRequest);
}
}).sendEmptyMessageDelayed(0, 1000);
Here is the link that provide complete solution for this.
Hope it will help you.
Yes, that behaviour is normal. AdView is a dynamic WebView which consumes about 50mb RAM. Most of the memory leaks occur when you rotate screen and instance of previous Activity is attached to an element like listener or thread. Here are some examples. To check whether your app leaks or not you can use LeakCanary or Android Studio.
To check leaks in Android Studio
Start Memory Profiler
Select Memory and "Dump Java Heap"
Export file as .hprof file
Drag .hprof file to Android Studio and look for Analyzer Tasks and push run button to check if your activity leaks.
Your app is still within an acceptable limit of RAM usage for most devices.
You can put android:largeHeap="true" in your AndroidManifest.xml file, so that your users won't get affected.
You are absolutely right. MobileAds.initilize() can be removed, and the application will work, BUT. When you request the first load of ads, the initilize() method will be called under the hood.
I recommend that you call this method as soon as possible. For example, in your Application class. Also, starting from version Admob 21.0.0, you can optimize the initialization process. Just add the following lines to your manifest
<meta-data
android:name="com.google.android.gms.ads.flag.OPTIMIZE_INITIALIZATION"
android:value="true"/>
<meta-data
android:name="com.google.android.gms.ads.flag.OPTIMIZE_AD_LOADING"
android:value="true"/>
i dont know if this will help but if you care about ram usage and you use ads in many activities you could start the ad mob from application class and that case the ad will only initialized once

Custom ads on admob android studio based on keyword

I have searched online but had not luck so far in my research, I have set up admobs in my android app and now I only want relevant ads to show up based on keyword that I set. My app is based on toys, so I only want ads related to toys to show
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
Looking at this: Admob ad on custom Dialog
This person has used:
AdRequest request = new AdRequest();
Set<String> keywords = new HashSet<String>();
keywords.add("game");
request.setKeywords(keywords);
However, this does not work.
I think you need this:
AdRequest request = new AdRequest.Builder()
.addKeyword("game").build();
.adView.loadAd(request);
You can try with this, but here are some examples, maybe you find what you allso need:
1.Test ads
Set up test ads by passing your hashed Device ID to AdRequest.Builder.addTestDevice:
AdRequest request = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR) // All emulators
.addTestDevice("AC98C820A50B4AD8A2106EDE96FB87D4") // An example device ID
.build();
2.Location
Location targeting information may also be specified in the AdRequest:
AdRequest request = new AdRequest.Builder()
.setLocation(location)
.build();
3.Gender
If your app already knows a user's gender, it can provide that information in the ad request for targeting purposes. The information is also forwarded to ad network mediation adapters if mediation is enabled.
AdRequest request = new AdRequest.Builder()
.setGender(AdRequest.GENDER_FEMALE)
.build();
4.Birthday
If your app already knows a user's birthday, it can provide that information in the ad request for targeting purposes. This information is also forwarded to ad network mediation adapters if mediation is enabled.
AdRequest request = new AdRequest.Builder()
.setBirthday(new GregorianCalendar(1985, 1, 1).getTime())
.build();
5.Designed for Families setting
If you have opted your app in to Google Play's Designed for Families program and you show ads in your app, you need to ensure those ads comply with the Designed for Families program requirements and ad policies.
Ad requests can be tagged as designed for families by setting the is_designed_for_families parameter to true in the extras:
Bundle extras = new Bundle();
extras.putBoolean("is_designed_for_families", true);
AdRequest request = new AdRequest.Builder()
.addNetworkExtrasBundle(AdMobAdapter.class, extras)
.build();
6.Child-directed setting
For purposes of the Children's Online Privacy Protection Act (COPPA), there is a setting called "tag for child directed treatment".
As an app developer, you can indicate whether you want Google to treat your content as child-directed when you make an ad request. If you indicate that you want Google to treat your content as child-directed, we will take steps to disable IBA and remarketing ads on that ad request. The setting can be used with all versions of the Google Play services SDK, via AdRequest.Builder.tagForChildDirectedTreatment(boolean):
If you set tagForChildDirectedTreatment to true, you will indicate that your content should be treated as child-directed for purposes of COPPA.
If you set tagForChildDirectedTreatment to false, you will indicate that your content should not be treated as child-directed for purposes of COPPA.
If you do not set tagForChildDirectedTreatment, ad requests will include no indication of how you would like your content treated with respect to COPPA.
AdRequest request = new AdRequest.Builder() .tagForChildDirectedTreatment(true) .build();
By setting this tag, you certify that this notification is accurate and you are authorized to act on behalf of the owner of the app. You understand that abuse of this setting may result in termination of your Google account.
7.Keyword
Add a keyword for targeting purposes.
AdRequest request = new AdRequest.Builder() .addKeyword(someKeyword) .build();
Loading an ad with targeting
Once your request targeting information is set, call loadAd on the AdView with your AdRequest instance.
AdRequest request = new AdRequest.Builder()
.setLocation(location)
.setGender(AdRequest.GENDER_FEMALE)
.setBirthday(new GregorianCalendar(1985, 1, 1).getTime())
.tagForChildDirectedTreatment(true)
.addKeyword("game")
.build();
adView.loadAd(request);
Additional information can be found on this link.
After doing some research, it does not look like keywords are supported.
There have been various questions over the years that all have the same answer:
The documentation for targeting ads does not include any information on using keywords.
You can add keywords to your AdRequest using addKeyword(String keyword) in AdRequest.Builder, which is documented here. An example call would be like below:
AdRequest adRequest = new AdRequest.Builder().addKeyword("game").build();
adView.loadAd(adRequest);
However, as stated above- it does not look like these keywords are being used on the backend.
The AdMob support site shows that there are three ways advertisers can choose to target their ads- context (keywords, presumably implicit rather than explicit), placement, and interest.
You can filter outside of your app by allowing and blocking ads, which if you truly do only want to show ads related to toys, then you will have to block everything except the toys category shown in the general category list.
You can try doing this :
AdRequest.Builder builder = new AdRequest.Builder()
.addKeyword("game");
Now you can build the adrequest.
As per the documentation to add a keyword for targeting purposes.
You can use this single line code.
public AdRequest.Builder addKeyword (String keyword)

onFailedToRecieveAd(Invalid Ad Request) message with AdMob

I've been trying to get AdMob to work for some time on my app. I keep getting onFailedToRecieveAd(Invalid Ad Request) message in the log. I've paired down my test application to this:
AdView adView;
LinearLayout ll;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adView = new AdView(this, AdSize.BANNER, "pub-2...............");//inserted my 16 digit pub id here
adView.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
ll.addView(adView);
setContentView(ll);
AdRequest adRequest = new AdRequest();
adRequest.addTestDevice("3...............");// 16 digits, tried other strings as
// follows:
//for addTestDevice I've tried several numbers, including the 16 digit device
// number given me by my "device id" application, the "0123456789ABCDEF" device number
// given by my console and device windows, the "CECE.........................." 32 digit
// device number my logcat file told me to use in a logcat message,
// "AdRequest.TEST_EMULATOR"
// which an admob example in the docs said to use, "9774d56d682e549c" which another
// admob docs example said to use.
adView.loadAd(adRequest);
I've also tried adView.loadAd(new AdRequest()); using no device id as in another one of the google admob example apps.
nothing has worked to show anything, it's not even creating space for the ad, just the onFailedToRecieveAd(Invalid Ad Request) message in the logcat
I've also included the necessary permissions and "com.google.ads.AdActivity" in the manifest.
Wow, after days of frustration and posts to various forums I've found the answer.
You have to go to your account on the Admob website to set up your specific app for the admob ads and get a new longer publisher number. My publisher number only started with 'pub-......' where my new number is longer and starts with 'ca-app-pub-.......'. I was curious about this from the start when I saw the 'ca-app-pub' preface in an example banner ap.
Nowhere on the Google Admob "Google Mobile Ads SDK" development site in the "banner ads 1" instructions (https://developers.google.com/mobile-ads-sdk/docs/admob/fundamentals?hl=en_US#android) does it mention having to go back to your admob account to set up your specific app for ads and get a new publisher number.
The stupid mistakes are the hardest to fix.
Be carefull with the id, there are 2 codes: the editor number (like this: pub-xxxxxxxxxxxxxxxx) and the other is the banner id (like this: ca-app-pub-xxxxxxxxxxxxxxxx/xxxxxxxxxx) (this one you need to use)
You need to use the last one, if you use the first doesnt work:)
It is not unusual to get a failed to receive ad. This is a normal message essentially saying that there are no ads to serve for your app at this point in time.
It means that your Admob integration is working, you are getting a response back from the server. As your app sends more requests it will be more likely to receive ad impressions.
Have you tried requesting an ad without setting the test device ID?
adView.loadAd(new AdRequest());
Try adding the following lines of code to get more info about the failure:
// Set AdListener
adView.setAdListener(new AdListener() {
#Override
public void onFailedToReceiveAd(Ad ad, ErrorCode error) {
System.err.println("Ad failed: " + ad.toString() + error.toString());
}
#Override
public void onReceiveAd(Ad ad) {
System.out.println("Ad received: " + ad.toString());
}
});

Admobs seems to allow only test ads to selected devices. Possible to make it generic?

I am using admobs in my android app and would like to test it with selected users on forums , family and friends.
I would like to display the test ads on their devices to avoid issues with conditions.
The doc says:
adRequest.addTestDevice("TEST_DEVICE_ID");// Test Android Device
But as I plan to share to non-tech people, I am pretty sure they won't be able to get their devices ID.
Is there a way to force displaying test ads on any devices?
Thank a lot.
You can use below line
adRequest.setTesting(true);
See I have used like this for testing purpose
AdRequest adRequest = new AdRequest();
adRequest.setTesting(true);
adView.loadAd(adRequest);
I don't know if there is a way to display test ads on select devices, but you could insert a view that has the same dimensions as the ad (50 by 350 I think?) and make it clear that an ad should go there. If you really wanted to you could even make it an image view, take a screen shot of Google's test ad, and create an onClickListener that sends you to Google.com.
This one was the correct answer
https://stackoverflow.com/a/8665279/327402
Not official but at least, that works!
String aid = Settings.Secure.getString(getContext().getContentResolver(), "android_id");
Object obj = null;
try {
((MessageDigest) (obj = MessageDigest.getInstance("MD5"))).update(
aid.getBytes(), 0, aid.length());
obj = String.format("%032X", new Object[] { new BigInteger(1,
((MessageDigest) obj).digest()) });
} catch (NoSuchAlgorithmException localNoSuchAlgorithmException) {
obj = aid.substring(0, 32);
}
adRequest.addTestDevice(obj.toString());

Categories

Resources