Search code examples
androidbashadbads

How to get Advertising Id using adb?


Currently, the only way I know to get Google Advertising Id (by hand) is to open settings and go to Accounts -> Google -> Ads. It is displayed under "Your advertising id"

However, I'd like to get Google Advertising Id via command line using adb. I want to automate this for testing.

For example, this is how I get android id:

android-sdks/platform-tools/adb shell settings get secure android_id

Is there an equivalent command for retrieving Advertising Id?

Thanks for your help in advance.


Solution

  • I devised a roundabout way to do this without rooting your phone. It requires some work with Android UI Testing and some bash shell scripting. All this code is written by me, so please let me know if you find any bugs or suggestions for improvement.

    Essentially we are going to show the settings screen for the "Google Ad Settings" and scrape the text with UI Automator, and use bash shell scripts to automate everything, including using grep to pull out the Advertising Id.

    Step 1. Create a Test Project

    Create a new project in Eclipse named GoogleAIDTest. Under Java Build Path, you will need to add the JUnit3 library, and then add External JARs uiautomator.jar and android.jar. You can find more details on this under the Android Docs: UI Testing / Configure your development environment

    Now add a namespace com.testing.googleaidtest to your project and then add a class called GoogleAidTest. The contents are as follows

    package com.testing.googleaidtest;
    
    import com.android.uiautomator.core.UiObject;
    import com.android.uiautomator.core.UiObjectNotFoundException;
    import com.android.uiautomator.core.UiSelector;
    import com.android.uiautomator.testrunner.UiAutomatorTestCase;
    
    public class GoogleAidTest extends UiAutomatorTestCase {
    
    public void testDemo() throws UiObjectNotFoundException {   
    
    
        final int AD_ID_LINEAR_LAYOUT_INDEX = 3;
        // Get the 4th Linear Layout (index 3) and find the RelativeLayout and the TextView within it
        UiObject childText = new UiObject(new UiSelector()
           .className("android.widget.LinearLayout").index(AD_ID_LINEAR_LAYOUT_INDEX)
           .childSelector(new UiSelector().className("android.widget.RelativeLayout"))
           .childSelector(new UiSelector().className("android.widget.TextView")));  
    
        assertTrue("Unable to find textView", 
                childText.exists());
    
        System.out.println("The content of this child is: " + childText.getText());
    
        // The content should be like this, with a \n as a separator between lines
        //Your advertising ID:
        //deadbeef-4242-6969-1337-0123456789ab
    
        int newlineIndex = childText.getText().indexOf('\n');
        if (newlineIndex != -1) {
            // Debug output to confirm there is a newline
            System.out.println("Index of newline is at index " + String.valueOf(newlineIndex));
    
            // Split the lines
            String[] parts = childText.getText().split("\n");
    
            // Confirm we have the second line 
            if (parts != null && parts[1] != null) {
                System.out.println("The Advertising Id for this device is: " + parts[1]);
            } else {
                System.out.println("Could not split the line!");
            }
        } else {
            System.out.println("Could not find the newline!");
        }
    
      } 
    

    Step 2. Build your testing jar

    You will need to run the following command to create "required build configuration files to build the output JAR"

    <android-sdk>/tools/android create uitest-project -n GoogleAidTest -t 1 -p <path to project>
    

    Once you're ready to build, run the following command in the base directory of your GoogleAidTest project:

    ant build
    

    In your bin directory you'll have a file called GoogleAidTest.jar, copy this to the same directory as your script in the next section (or wherever you want really, but you will have to adjust the following script for your environment)

    Step 3. Make a shell script named "getgaid.sh" for showing the AdSettingsActivity and scraping the Google Advertising Id

    #!/bin/sh
    # Only works on devices with API level 16 and above (due to uiautomator) 
    ##
    # NOTE:
    # This script requires that you build GoogleAidTest beforehand and put the jar file in current working directory
    
    # Change adbPath to your own android sdk path
    adbPath="$HOME/android-sdks/platform-tools/adb"
    
    # Check for adb and GoogleAidTest.jar existence before test
    if [ ! -f "$adbPath" ]; then 
        echo "adb not found!"
    elif [ ! -f "GoogleAidTest.jar" ]; then
        echo "GoogleAidTest.jar not found!"
    else
        # Start Ad Settings Activity
        $adbPath shell am start -n com.google.android.gms/.ads.settings.AdsSettingsActivity
    
        # Push the GoogleAidTest jar to the phone, GoogleAidTest.jar should be in the current working directory
        $adbPath push GoogleAidTest.jar /data/local/tmp/
    
        # Run the test, using grep to pull out the relevant line
        $adbPath shell uiautomator runtest GoogleAidTest.jar -c com.testing.googleaidtest.GoogleAidTest | grep "Advertising Id"
    
        # Stop the Ad Settings Activity to clean up 
        $adbPath shell am force-stop com.google.android.gms
    fi
    

    Step 4. Make your script executable

    chmod +x getgaid.sh
    

    Step 5. Run script

    ./getgaid.sh
    

    The settings screen for Ads will be briefly displayed on your device. The script is now scraping the Advertising Id text from the UI. After completion, the activity is stopped.

    On the command line, the Google Advertising Id will be displayed, for easy copy-and-paste!

    The Advertising Id for this device is: deadbeef-4242-6969-1337-0123456789ab
    

    Limitations

    • Please note that this will only work on devices with API level 16 above
    • If the UI for the "Ads" setting page (AdsSettingsActivity) changes, the test script may no longer function. I used UI Automator Viewer (found in android-sdks/tools/uiautomatorviewer) to locate the correct indexes of the controls. Please adjust as needed.