How to Get Android Advertisement ID (AAID) programmatically

sometimes we need to get the android advertisement id AAID for android device, when we place google ads or Facebook ads to our Android app or any other functions we need to place the unique AAID for testing purpose.

here I will tell you the simple method to get the AAID of your android device so that you can test your demo ads properly.

Info adInfo = null;
try {
    adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
} catch (IOException e) {
    // ...
} catch ( GooglePlayServicesRepairableException e) {
    // ...
} catch (GooglePlayServicesNotAvailableException e) {
    // ...
}
String android_id = adInfo.getId();
Log.d("DEVICE_ID",android_id);
 

the above block provides the android device AAID, but it may crash to some device with the error:

java.lang.IllegalStateException: Calling this from your main thread can lead to deadlock

so you need to try it with async task or any you can create any thread as per your code structure, here I am using async task to perfom the task

 AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                String token = null;
                Info adInfo = null;
                try {
                    adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
                } catch (IOException e) {
                    // ...
                } catch ( GooglePlayServicesRepairableException e) {
                    // ...
                } catch (GooglePlayServicesNotAvailableException e) {
                    // ...
                }
                String android_id = adInfo.getId();
                Log.d("DEVICE_ID",android_id);

                return android_id;
            }

            @Override
            protected void onPostExecute(String token) {
                Log.i(TAG, "DEVICE_ID Access token retrieved:" + token);
            }

        };
        task.execute();

you are done, the above code will run in the async task and will not block your main thread and will get the android advertising id AAID.

cheers !!
Happy Coading

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Stay in Touch

Related Articles