Android獲得設(shè)備狀態(tài)信息、Mac地址、IP地址的方法
前言
在APP開發(fā)時,經(jīng)常會遇到要獲取手機狀態(tài)信息的場景,像升級時獲取版本號,像發(fā)生異常時要收集手機信息等等。有些軟件還要根據(jù)Mac地址來判定當(dāng)前用戶以前是否登錄過。下面將一一介紹獲取這些手機狀態(tài)信息的方法。
1 通過build獲取手機硬件信息
- 運用反射獲取Build信息,然后從build中得到對應(yīng)字段的值。這種情況適用于獲取所有的build信息。
- 或者直接調(diào)用Build類直接拿里面的字段名,如:android.os.Build.MODEL; // 手機型號 。這是為了獲取單獨某個手機信息的方法,直接調(diào)用Build的字段即可拿到對應(yīng)信息,簡單快捷。
- 別忘了加權(quán)限
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
下面是Build類的字段所對應(yīng)的信息
String BOARD The name of the underlying board, like "goldfish".基板名 String BOOTLOADER The system bootloader version number. String BRAND The brand (e.g., carrier) the software is customized for, if any.品牌名 String CPU_ABI The name of the instruction set (CPU type + ABI convention) of native code. String CPU_ABI2 The name of the second instruction set (CPU type + ABI convention) of native code. String DEVICE The name of the industrial design.品牌型號名,如小米4對應(yīng)cancro String DISPLAY A build ID string meant for displaying to the user String FINGERPRINT A string that uniquely identifies this build.包含制造商,設(shè)備名,系統(tǒng)版本等諸多信息 String HARDWARE The name of the hardware (from the kernel command line or /proc). String HOST String ID Either a changelist number, or a label like "M4-rc20". String MANUFACTURER The manufacturer of the product/hardware. String MODEL The end-user-visible name for the end product. String PRODUCT The name of the overall product. String RADIO The radio firmware version number. String SERIAL A hardware serial number, if available. String TAGS Comma-separated tags describing the build, like "unsigned,debug". long TIME 當(dāng)前時間,毫秒值 String TYPE The type of build, like "user" or "eng". String UNKNOWN Value used for when a build property is unknown. String USER
//運用反射得到build類里的字段
Field[] fields = Build.class.getDeclaredFields();
//遍歷字段名數(shù)組
for (Field field : fields) {
try {
//將字段都設(shè)為public可獲取
field.setAccessible(true);
//filed.get(null)得到的即是設(shè)備信息
haspmap.put(field.getName(), field.get(null).toString());
Log.d("CrashHandler", field.getName() + " : " + field.get(null));
} catch (Exception e) {
}
}
下面是小米4對應(yīng)的設(shè)備信息
D/CrashHandler: BOARD : MSM8974 D/CrashHandler: BOOTLOADER : unknown D/CrashHandler: BRAND : Xiaomi D/CrashHandler: CPU_ABI : armeabi-v7a D/CrashHandler: CPU_ABI2 : armeabi D/CrashHandler: DEVICE : cancro D/CrashHandler: DISPLAY : MMB29M D/CrashHandler: FINGERPRINT : Xiaomi/cancro_wc_lte/cancro:6.0.1/MMB29M/V8.1.3.0.MXDCNDI:user/release-keys D/CrashHandler: HARDWARE : qcom D/CrashHandler: HOST : c3-miui-ota-bd43 D/CrashHandler: ID : MMB29M D/CrashHandler: IS_DEBUGGABLE : false D/CrashHandler: MANUFACTURER : Xiaomi D/CrashHandler: MODEL : MI 4LTE D/CrashHandler: PRODUCT : cancro_wc_lte D/CrashHandler: RADIO : unknown //設(shè)備的序列號碼-SERIAL D/CrashHandler: SERIAL : abcdefgh D/CrashHandler: SUPPORTED_32_BIT_ABIS : [Ljava.lang.String;@76b6d2b D/CrashHandler: SUPPORTED_64_BIT_ABIS : [Ljava.lang.String;@e42c588 D/CrashHandler: SUPPORTED_ABIS : [Ljava.lang.String;@9cdbb21 D/CrashHandler: TAG : Build D/CrashHandler: TAGS : release-keys D/CrashHandler: TIME : 1478606340000 D/CrashHandler: TYPE : user D/CrashHandler: UNKNOWN : unknown D/CrashHandler: USER : builder
2.通過getSystemService()來獲取Ip地址
Context.getSystemService()這個方法是非常實用的方法,只須在參數(shù)里輸入一個String 字符串常量就可得到對應(yīng)的服務(wù)管理方法,可以用來獲取絕大部分的系統(tǒng)信息,各個常量對應(yīng)的含義如下。
WINDOW_SERVICE (“window”)
The top-level window manager in which you can place custom windows. The returned object is a WindowManager.
LAYOUT_INFLATER_SERVICE (“l(fā)ayout_inflater”)
A LayoutInflater for inflating layout resources in this context.
ACTIVITY_SERVICE (“activity”)
A ActivityManager for interacting with the global activity state of the system.
POWER_SERVICE (“power”)
A PowerManager for controlling power management.
ALARM_SERVICE (“alarm”)
A AlarmManager for receiving intents at the time of your choosing.
NOTIFICATION_SERVICE (“notification”)
A NotificationManager for informing the user of background events.
KEYGUARD_SERVICE (“keyguard”)
A KeyguardManager for controlling keyguard.
LOCATION_SERVICE (“l(fā)ocation”)
A LocationManager for controlling location (e.g., GPS) updates.
SEARCH_SERVICE (“search”)
A SearchManager for handling search.
VIBRATOR_SERVICE (“vibrator”)
A Vibrator for interacting with the vibrator hardware.
CONNECTIVITY_SERVICE (“connection”)
A ConnectivityManager for handling management of network connections.
WIFI_SERVICE (“wifi”)
A WifiManager for management of Wi-Fi connectivity.
WIFI_P2P_SERVICE (“wifip2p”)
A WifiP2pManager for management of Wi-Fi Direct connectivity.
INPUT_METHOD_SERVICE (“input_method”)
An InputMethodManager for management of input methods.
UI_MODE_SERVICE (“uimode”)
An UiModeManager for controlling UI modes.
DOWNLOAD_SERVICE (“download”)
A DownloadManager for requesting HTTP downloads
BATTERY_SERVICE (“batterymanager”)
A BatteryManager for managing battery state
JOB_SCHEDULER_SERVICE (“taskmanager”)
A JobScheduler for managing scheduled tasks
NETWORK_STATS_SERVICE (“netstats”)
A NetworkStatsManager for querying network usage statistics.
Note: System services obtained via this API may be closely associated with the Context in which they are obtained from. In general, do not share the service objects between various different contexts (Activities, Applications, Services, Providers, etc.)
Parameters
name
The name of the desired service.
Returns
The service or null if the name does not exist.
要獲取IP地址需要用到Context.CONNECTIVITY_SERVICE,這個常量所對應(yīng)的網(wǎng)絡(luò)連接的管理方法。
代碼如下需要權(quán)限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
/**獲得IP地址,分為兩種情況,一是wifi下,二是移動網(wǎng)絡(luò)下,得到的ip地址是不一樣的*/
public static String getIPAddress() {
Context context=MyApp.getContext();
NetworkInfo info = ((ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info != null && info.isConnected()) {
if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//當(dāng)前使用2G/3G/4G網(wǎng)絡(luò)
try {
//Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
} else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//當(dāng)前使用無線網(wǎng)絡(luò)
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
//調(diào)用方法將int轉(zhuǎn)換為地址字符串
String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
return ipAddress;
}
} else {
//當(dāng)前無網(wǎng)絡(luò)連接,請在設(shè)置中打開網(wǎng)絡(luò)
}
return null;
}
/**
* 將得到的int類型的IP轉(zhuǎn)換為String類型
* @param ip
* @return
*/
public static String intIP2StringIP(int ip) {
return (ip & 0xFF) + "." +
((ip >> 8) & 0xFF) + "." +
((ip >> 16) & 0xFF) + "." +
(ip >> 24 & 0xFF);
}
3.獲得Mac地址
我們知道m(xù)ac地址是網(wǎng)卡的唯一標識,通過這個可以判斷網(wǎng)絡(luò)當(dāng)前連接的手機設(shè)備有幾臺。代碼如下:
public static String getMacAddress(){
/*獲取mac地址有一點需要注意的就是android 6.0版本后,以下注釋方法不再適用,不管任何手機都會返回"02:00:00:00:00:00"這個默認的mac地址,這是googel官方為了加強權(quán)限管理而禁用了getSYstemService(Context.WIFI_SERVICE)方法來獲得mac地址。*/
// String macAddress= "";
// WifiManager wifiManager = (WifiManager) MyApp.getContext().getSystemService(Context.WIFI_SERVICE);
// WifiInfo wifiInfo = wifiManager.getConnectionInfo();
// macAddress = wifiInfo.getMacAddress();
// return macAddress;
String macAddress = null;
StringBuffer buf = new StringBuffer();
NetworkInterface networkInterface = null;
try {
networkInterface = NetworkInterface.getByName("eth1");
if (networkInterface == null) {
networkInterface = NetworkInterface.getByName("wlan0");
}
if (networkInterface == null) {
return "02:00:00:00:00:02";
}
byte[] addr = networkInterface.getHardwareAddress();
for (byte b : addr) {
buf.append(String.format("%02X:", b));
}
if (buf.length() > 0) {
buf.deleteCharAt(buf.length() - 1);
}
macAddress = buf.toString();
} catch (SocketException e) {
e.printStackTrace();
return "02:00:00:00:00:02";
}
return macAddress;
}
4.獲取手機號碼、IMEI碼
/**獲取手機的IMEI號碼*/
public static String getPhoneIMEI() {
TelephonyManager mTm = (TelephonyManager) MyApp.getContext().getSystemService(Context.TELEPHONY_SERVICE);
String imei = mTm.getDeviceId();
String imsi = mTm.getSubscriberId();
String mtype = android.os.Build.MODEL; // 手機型號
String numer = mTm.getLine1Number(); // 手機號碼,有的可得,有的不可得
return imei;
}
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
- Android開發(fā)獲取手機內(nèi)網(wǎng)IP地址與外網(wǎng)IP地址的詳細方法與源碼實例
- Android中使用adb命令通過IP地址連接手機
- Android實現(xiàn)IP地址輸入框的方法示例代碼
- Android開發(fā)實現(xiàn)在Wifi下獲取本地IP地址的方法
- Android 判斷ip地址合法實現(xiàn)代碼
- Android 獲取IP地址的實現(xiàn)方法
- android 獲取本機的IP地址和mac物理地址的實現(xiàn)方法
- android實現(xiàn)獲取有線和無線Ip地址的方法
- Android手機獲取IP地址的兩種方法
- Android開發(fā)準確獲取手機IP地址的兩種方式
相關(guān)文章
Android AAPT(Android Asset Packaging Too
AAPT - Android Asset Packaging Tool作用AAPT基本命令A(yù)APT編譯資源源碼解析AAPT打包和系統(tǒng)不一致的資源2024-04-04
Android 兩個Fragment之間的跳轉(zhuǎn)和數(shù)據(jù)的傳遞實例詳解
這篇文章主要介紹了Android 兩個Fragment之間的跳轉(zhuǎn)和數(shù)據(jù)的傳遞實例詳解的相關(guān)資料,這里說明實現(xiàn)的思路及實現(xiàn)方法,需要的朋友可以參考下2017-07-07
Android使用Intent傳遞組件大數(shù)據(jù)
這篇文章主要介紹了Android使用Intent傳遞組件大數(shù)據(jù),文章圍繞主題展開詳細的內(nèi)容詳情,感興趣的朋友可以參考一下2022-07-07
Android WebView自定義長按選擇實現(xiàn)收藏/分享選中文本功能
這篇文章主要介紹了Android WebView自定義長按選擇實現(xiàn)收藏/分享選中文本功能,需要的朋友可以參考下2017-06-06
Android Notification.Builder通知案例分享
這篇文章主要為大家分享了Android Notification.Builder通知案例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10

