Created
March 22, 2016 02:55
-
-
Save keima/73a62d167acd1131ff32 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.ContentResolver; | |
import android.content.Context; | |
import android.os.Build; | |
import android.provider.Settings; | |
import android.util.Log; | |
import com.google.android.gms.ads.AdRequest; | |
import java.math.BigInteger; | |
import java.security.MessageDigest; | |
import java.security.NoSuchAlgorithmException; | |
import java.util.Locale; | |
/** | |
* AdMobのaddTestDeviceを自動で行えたらいいなぁと思い実装。 | |
* コードの実装は PlayServices 8.4.0 の com/google/android/gms/ads/internal/util/client/zza.class の | |
* デコンパイラ内容から拝借。 | |
*/ | |
public class AdMobUtil { | |
private static final String TAG = AdMobUtil.class.getSimpleName(); | |
public static AdRequest.Builder addTestDeviceAutomatically(Context context, AdRequest.Builder builder) { | |
String deviceID = getOwnDeviceID(context); | |
Log.d(TAG, "addTestDeviceAutomatically: deviceId:" + deviceID); | |
return builder.addTestDevice(deviceID); | |
} | |
private static String getOwnDeviceID(Context context) { | |
ContentResolver cr = context.getContentResolver(); | |
String androidId = cr == null ? null : Settings.Secure.getString(cr, Settings.Secure.ANDROID_ID); | |
return convertAndroidIdToDeviceId(androidId != null && !isGeneric() ? androidId : "emulator"); | |
} | |
private static String convertAndroidIdToDeviceId(String androidId) { | |
int i = 0; | |
while (i < 2) { | |
try { | |
MessageDigest md5 = MessageDigest.getInstance("MD5"); | |
md5.update(androidId.getBytes()); | |
return String.format(Locale.US, "%032X", new Object[]{new BigInteger(1, md5.digest())}); | |
} catch (NoSuchAlgorithmException e) { | |
++i; | |
} | |
} | |
return null; | |
} | |
private static boolean isGeneric() { | |
return Build.DEVICE.startsWith("generic"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment