我正在开发一款安卓应用,想要接收推送通知。但是为了使其成功,我需要一个设备ID。由于我没有任何安卓手机,所以我在模拟器中测试该应用。那么我的问题是,我能否为我的模拟器获取设备ID呢?
在Android系统中,你无法获取设备ID,但你可以获得IMEI号码用于推送通知。因为所有的设备都有不同的IMEI号码。在模拟器中,默认情况下会显示0000000000000作为IMEI号码,但是在真实设备中,你会得到正确的号码。以下是获取IMEI号码的代码:
TelephonyManager telephonyManager1 = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String imei = telephonyManager1.getDeviceId();
通过安卓模拟器:
public String getDeviceID(Context context) {
TelephonyManager manager =
(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
String deviceId;
if (manager.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE) {
//Tablet
deviceId = Secure.getString(this.getContentResolver(),
Secure.ANDROID_ID);
} else {
//Mobile
deviceId = manager.getDeviceId();
}
return deviceId;
}
这对我有效
public static String getIMEI() {
String IMEI = Settings.Secure.getString(getApplicationContext().getContentResolver(),Settings.Secure.ANDROID_ID);
return IMEI;
}
获取模拟器的设备ID >>>
在 onCreate() 方法中添加以下两行代码:
String android_id = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
String deviceId = md5(android_id).toUpperCase();
Log.i("device id=",deviceId);
public String md5(String s) {
try {
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
for (int i=0; i<messageDigest.length; i++)
hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
要找到设备ID,只需在你的Android Studio中运行应用程序并打开logcat,然后在搜索栏中输入“device id”。