Skip to content

Instantly share code, notes, and snippets.

@s0h4m
Created June 8, 2016 07:10
Show Gist options
  • Save s0h4m/d033263b7a801d9381432b2c400bb8a4 to your computer and use it in GitHub Desktop.
Save s0h4m/d033263b7a801d9381432b2c400bb8a4 to your computer and use it in GitHub Desktop.
Creates an anonymous id for analytics specifically for play-services devices. This can be derived from advertising-id or even the fem token.
import android.content.Context;
import android.support.annotation.Nullable;
import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.firebase.iid.FirebaseInstanceId;
import java.io.IOException;
/**
* Generates an ID for play-services powered devices
*/
public class FirebaseId extends Id {
/**
* Get an analytics ID for play-services powered devices, we will try the following
* 1. get the advertising id if possible
* 2. get the fcm token if possible
* 3. get the UUID id
* @param context
* @return
*/
@Override
public String getId(final Context context) {
// try to get an advertising id
String adId = getAdvertisingIdIfApplicable(context);
if (adId != null) return adId;
// try to get the fcm token
String firebaseToken = getFirebaseTokenIfPossible();
if (firebaseToken != null) return firebaseToken;
// get an id from UUID
return getUUIDPoweredId();
}
/**
* Get the advertising id if it is enabled
* Found in play-services-basement
* @param context
* @return
*/
@Nullable
private String getAdvertisingIdIfApplicable(final Context context) {
try {
AdvertisingIdClient.Info info = AdvertisingIdClient.getAdvertisingIdInfo(context);
if (info.isLimitAdTrackingEnabled()) {
return info.getId();
}
} catch (IOException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
}
return null;
}
/**
* Get the FCM token if possible
* @return
*/
@Nullable
private String getFirebaseTokenIfPossible() {
try {
return FirebaseInstanceId.getInstance().getToken();
} catch (Exception exception) {
exception.printStackTrace();
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment