Andorid开发获取IMEI号,获取ICCID,获取IP
有时候我们为了获取到一些手机的信息作为唯一的标记,或者开发需要。
我们如何拿IMEI号,如何拿到ICCID,IP地址呢?
IMEI号
国际移动设备识别码(International Mobile Equipment Identity,IMEI),即通常所说的手机序列号、手机“串号”,用于在移动电话网络中识别每一部独立的手机等移动通信设备,相当于移动电话的身份证。
权限:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
获取代码:
public String GetIMEI() {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (tm == null) return null;
if (ActivityCompat.checkSelfPermission(context,
Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
return "";
}
return tm.getDeviceId();
}
ICCID
ICCID:Integrate circuit card identity 集成电路卡识别码即SIM卡卡号,相当于手机号码的身份证。 ICCID为IC卡的唯一识别号码,共有20位字符组成,其编码格式为:XXXXXX 0MFSS YYGXX XXXX。
Requires Permission: READ_PRIVILEGED_PHONE_STATE
Permission is only granted to system apps
<uses-permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE" />
获取代码:
private String getICCID() {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (tm == null) return null;
String simSerialNumber = tm.getSimSerialNumber();
SobLog.d(TAG, "simSerialNumber == > " + simSerialNumber);
return simSerialNumber;
}
如查没有sim卡的话,就获取不到了
IP地址
private String getIp() {
String ip = null;
ConnectivityManager conMann = (ConnectivityManager)
requireContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mobileNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo wifiNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mobileNetworkInfo.isConnected()) {
ip = getLocalIpAddress();
System.out.println("IP:" + ip);
} else if (wifiNetworkInfo.isConnected()) {
WifiManager wifiManager = (WifiManager) SettingApp.getInstance().getApplicationContext()
.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
ip = intToIp(ipAddress);
System.out.println("WI-FI IP:" + ip);
}
IcLog.d(TAG, "ip ==> " + ip);
return ip;
}
public String intToIp(int ipInt) {
StringBuilder sb = new StringBuilder();
sb.append(ipInt & 0xFF).append(".");
sb.append((ipInt >> 8) & 0xFF).append(".");
sb.append((ipInt >> 16) & 0xFF).append(".");
sb.append((ipInt >> 24) & 0xFF);
return sb.toString();
}
public String getLocalIpAddress() {
try {
String ipv4 = null;
ArrayList<NetworkInterface> list = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface ni : list) {
ArrayList<InetAddress> addresses = Collections.list(ni.getInetAddresses());
for (InetAddress address : addresses) {
if (!address.isLoopbackAddress() && address instanceof Inet4Address) {
return ipv4;
}
}
}
} catch (SocketException ex) {
Log.e("ip get error", ex.toString());
}
return null;
}