[android] How can I get device ID for Admob

I'm using Eclipse to develop applications for android, and I want to integrate Admob to make money. The tutorial says I should watch the LogCat to find ID, but where is it? alt text

When I run in either the test mode or the real mode, sometimes the eclipse will notify that Ads returned, yet it does not show in the emu... can anyone explain?

This question is related to android eclipse admob

The answer is


  • Is your app published on Play store -- with live ads:

If your app is on Play store showing live ads -- you can't use live ads for testing -- add your device ID in code to get test ads from Admob on your real device. Never use live ads during development or testing.

To get real device ID in logcat,

  1. Connect your device in USB debug mode to Android Studio

USB debug mode(Developer option)

  1. Open any app on your device which shows live ads from Admob: On the connected device, if you have your app downloaded from play store(showing live ads) open that app or else open any other app that shows live Admob ads. Your device should have an internet connection.

  2. Filter the logcat with 'device' as shown below to get test device

Test Device ID in logcat

Read Admob ad testing on device - device IDs can change for more


If you are testing your app on actual device then you can try this small android app which gives you the device id:

https://play.google.com/store/apps/details?id=pe.go_com.admobdeviceidfinder&hl=en

You will get the hashed device id directly. Hope this helps.


To get the device id, connect your phone to USB and open logcat in android studio Use the code below (make sure you have USB debugging enabled in your device). Then open any app (download any random app from play store) which has google Ad. In the Logcat type "set" as shown in the image. Your device id is shown highlighted in the image as

setTestDeviceIds(Arrays.asList("CC9DW7W7R4H0NM3LT9OLOF7455F8800D")).

enter image description here

Use the Test Device in your code as shown

val adRequest = AdRequest
        .Builder()
        .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
        .addTestDevice("CC9DW7W7R4H0NM3LT9OLOF7455F8800D")
        .build()

Add this class to your project

import android.content.Context;
import android.provider.Settings;
import android.text.TextUtils;

import com.google.android.gms.ads.AdRequest;
import java.io.UnsupportedEncodingException;

public class AdsHelper {
public static AdRequest createRequest(Context context) {
    AdRequest.Builder adRequest = new AdRequest.Builder();
    adRequest.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
    if (BuildConfig.DEBUG) {
        String deviceId = MD5(getDeviceId(context));
        if (!TextUtils.isEmpty(deviceId)) {
            adRequest.addTestDevice(deviceId.toUpperCase());
        }
    }

    return adRequest.build();
}



    private static String MD5(String md5) {
        if (TextUtils.isEmpty(md5)) return null;
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] array = md.digest(md5.getBytes("UTF-8"));
            StringBuilder sb = new StringBuilder();
            for (byte anArray : array) {
                sb.append(Integer.toHexString((anArray & 0xFF) | 0x100).substring(1, 3));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException ignored) {
        } catch(UnsupportedEncodingException ignored){
        }
        return null;
    }

    private static String getDeviceId(Context context) {
        try {
            return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        } catch (Exception e) {
            return "";
        }

    }
}

Usage:

AdRequest adRequest = AdsHelper.createRequest(this);

If you don't get it in the logcat just put any device id and load you Ads and run your app then go to the log you will get it like that I/Ads: Use AdRequest.Builder.addTestDevice("XXXXXXXXXXXXXXXXXXXXXXXXX") to get test ads on this device. after that put it and run your application again.


Another easiest way to show test ads is to use test device id for banner to show admob test ads for all devices. "ca-app-pub-3940256099942544/6300978111" . This admob test ads id was noted in the admob tutorial of google: link. This is the quote from the above link: enter image description here

  • This is the test device id for interstitial "ca-app-pub-3940256099942544/1033173712" . This also was used in interstitial tutorial

Works to this way:

InterstitialAd mInterstitial = new InterstitialAd(this);
    mInterstitial.setAdUnitId("your id");
    AdRequest adRequest = new AdRequest.Builder()
    .addTestDevice("some words")
    .build();
    mInterstitial.loadAd(adRequest);

After run the app... Go in Logcat put in Verbose put in the search field AdRequest, so the id device shows donw.

enter image description here

.addTestDevice("put the id here");

I hope have helped;


Something similar to Google Ads, from the documentation:

public AdRequest.Builder addTestDevice (String deviceId)

Causes a device to receive test ads. The deviceId can be obtained by viewing the logcat output after creating a new ad. For emulators, use DEVICE_ID_EMULATOR.

for example my Test Device id displayed in LogCat is "B86BC9402A69B031A516BC57F7D3063F":

AdRequest adRequest = new AdRequest.Builder() 
        .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
        .addTestDevice("B86BC9402A69B031A516BC57F7D3063F")
        .build();

I have a few devices I was testing on, and didn't want to manually get the DeviceID for each one. The answers here to programmatically get the DeviceIDs were not working for me (Missing zeros) which caused real ads to be shown instead of test ads.

I put this in my Application class onCreate, and then exposed deviceId using a getter method so that it can be accessed throughout.

@Override
public void onCreate() {        
    super.onCreate();

    String androidId =  Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
    deviceId = MD5(androidId).toUpperCase();        
}  

public static String getDeviceId() {
    return deviceId;
}

private static String deviceId;

And the MD5 method;

public String MD5(String md5) {
   try {
        java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
        byte[] array = md.digest(md5.getBytes());
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; ++i) {
            sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
        }
        return sb.toString();
    } catch (java.security.NoSuchAlgorithmException e) {
    }
    return null;
}

Then using this whenever I create an AdRequest object:

if(BuildConfig.DEBUG) {
     AdRequest adRequest = new AdRequest.Builder()
          .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
          .addTestDevice(Application.getDeviceId())
          .build();
     adView.loadAd(adRequest);
} else {
     AdRequest adRequest = new AdRequest.Builder()
          .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
          .build();
     adView.loadAd(adRequest);
}

To get the Hash Device ID

inside the oncreate

String android_id = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
        String deviceId = md5(android_id).toUpperCase();
Log.i("device id=",deviceId);

then add this class for md5 ()

public String md5(String s) {
        try {
            // Create MD5 Hash
            MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
            digest.update(s.getBytes());
            byte messageDigest[] = digest.digest();

            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            for (int i=0; i<messageDigest.length; i++)
                hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

app: build.gradle

dependencies {
...
compile 'com.google.firebase:firebase-ads:10.0.1'
...
}

Your Activity:

 AdRequest.Builder builder = new AdRequest.Builder();
        if(BuildConfig.DEBUG){

            String android_id = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
            String deviceId = io.fabric.sdk.android.services.common.CommonUtils.md5(android_id).toUpperCase();
            builder.addTestDevice(deviceId);
        }
        AdRequest adRequest = builder.build();
    adView.loadAd(adRequest);

If you are displaying ads using XML layout and if you already have "ads:testDevices=" in your layout XML file, AdMob will NOT print the "To get test ads on this device..." message in the LogCat output. Take that out and then you will see the LogCat message.

Here is a nice tutorial on how to find device id in LogCat: http://webhole.net/2011/12/02/android-sdk-tutorial-get-admob-test-device-id/


The accepted answers will work if you are only testing on the Emulator or on a few devices, but if you are testing on a plethora of devices, you may need some means of prorammatically adding the running device's device ID.

The following code will make the current running device into an adview test device programmatically

...
    if(YourApplication.debugEnabled(this)) //debug flag from somewhere that you set
    {

        String android_id = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
        String deviceId = md5(android_id).toUpperCase();
        mAdRequest.addTestDevice(deviceId);
        boolean isTestDevice = mAdRequest.isTestDevice(this);

        Log.v(TAG, "is Admob Test Device ? "+deviceId+" "+isTestDevice); //to confirm it worked
    }

You need to use the md5 of the Android ID, and it needs to be upper case. Here is the md5 code I used

public static final String md5(final String s) {
    try {
        // Create MD5 Hash
        MessageDigest digest = java.security.MessageDigest
                .getInstance("MD5");
        digest.update(s.getBytes());
        byte messageDigest[] = digest.digest();

        // Create Hex String
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < messageDigest.length; i++) {
            String h = Integer.toHexString(0xFF & messageDigest[i]);
            while (h.length() < 2)
                h = "0" + h;
            hexString.append(h);
        }
        return hexString.toString();

    } catch (NoSuchAlgorithmException e) {
        Logger.logStackTrace(TAG,e);
    }
    return "";
}

EDIT: Apparently that MD5 method isnt perfect, and it was suggested to try https://stackoverflow.com/a/21333739/2662474 I no longer need this feature so I havent tested. Good luck!


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to eclipse

How do I get the command-line for an Eclipse run configuration? My eclipse won't open, i download the bundle pack it keeps saying error log strange error in my Animation Drawable How to uninstall Eclipse? How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Class has been compiled by a more recent version of the Java Environment Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9 "The POM for ... is missing, no dependency information available" even though it exists in Maven Repository The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

Examples related to admob

Plugin with id 'com.google.gms.google-services' not found Error "library not found for" after putting application in AdMob Does this app use the Advertising Identifier (IDFA)? - AdMob 6.8.0 error: No resource identifier found for attribute 'adSize' in package 'com.google.example' main.xml How can I get device ID for Admob