com.segment.analytics.GetAdvertisingIdTask Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of analytics-core Show documentation
Show all versions of analytics-core Show documentation
The hassle-free way to add analytics to your Android app.
package com.segment.analytics;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Pair;
/**
* An {@link AsyncTask} that fetches the advertising info and attaches it to the given {@link
* AnalyticsContext} instance.
*/
class GetAdvertisingIdTask extends AsyncTask> {
final AnalyticsContext analyticsContext;
GetAdvertisingIdTask(AnalyticsContext analyticsContext) {
this.analyticsContext = analyticsContext;
}
@Override protected Pair doInBackground(Context... contexts) {
final Context context = contexts[0];
try {
Object advertisingInfo =
Class.forName("com.google.android.gms.ads.identifier.AdvertisingIdClient")
.getMethod("getAdvertisingIdInfo", Context.class)
.invoke(null, context);
Boolean isLimitAdTrackingEnabled = (Boolean) advertisingInfo.getClass()
.getMethod("isLimitAdTrackingEnabled")
.invoke(advertisingInfo);
String id = (String) advertisingInfo.getClass().getMethod("getId").invoke(advertisingInfo);
return Pair.create(id, isLimitAdTrackingEnabled);
} catch (Exception ignored) {
return null;
}
}
@Override protected void onPostExecute(Pair info) {
super.onPostExecute(info);
if (info != null) {
AnalyticsContext.Device device = analyticsContext.device();
if (device != null) {
device.putAdvertisingInfo(info.first, info.second);
}
}
}
}