It makes a lot of sense that Android ad SDKs will use Android\'s the new advertiser id.
It seems that you can only get the id by using the google services sdk, as me
Adrian's solution is excellent, and I use it myself.
However, today I discovered that it has a bug when Google Play Services is not installed on the device. You will get a message about leaking a ServiceConnection
when your activity/service is stopped. This is actually a bug in Context.bindService
: when binding to the service fails (in this case because Google Play Services is not installed), Context.bindService
returns false, but it doesn't clear the reference to the ServiceConnection
, and expects you to call Context.unbindService
even though the service doesn't exist!
The workaround is to change the code of getAdvertisingIdInfo
like this:
public static AdInfo getAdvertisingIdInfo(Context context) throws Exception {
if(Looper.myLooper() == Looper.getMainLooper())
throw new IllegalStateException("Cannot be called from the main thread");
try {
PackageManager pm = context.getPackageManager();
pm.getPackageInfo("com.android.vending", 0);
} catch(Exception e) {
throw e;
}
AdvertisingConnection connection = new AdvertisingConnection();
Intent intent = new Intent("com.google.android.gms.ads.identifier.service.START");
intent.setPackage("com.google.android.gms");
try {
if(context.bindService(intent, connection, Context.BIND_AUTO_CREATE)) {
AdvertisingInterface adInterface = new AdvertisingInterface(connection.getBinder());
AdInfo adInfo = new AdInfo(adInterface.getId(), adInterface.isLimitAdTrackingEnabled(true));
return adInfo;
}
} catch(Exception exception) {
throw exception;
} finally {
context.unbindService(connection);
}
throw new IOException("Google Play connection failed");
}
That way Context.unbindService
will be called even if Context.bindService
returns false
.