編輯:關於 Android 程式設計
在網路相關的開發中,取得裝置的 IP 位址與實體位址是很常見的需求。以下整理幾種實用的實作方式。
public static String getLocalIPAddress() {
try {
for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e("BaseScanTvDeviceClient", "獲取本機IP false =" + ex.toString());
}
return null;
}
這種方式會遍歷所有網路介面,找出第一個非 loopback 的 IPv4 位址。
public static String getLocalIPAddress(Context context) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
return Formatter.formatIpAddress(wifiInfo.getIpAddress());
}
在已連上 Wi-Fi 的情況下,這是取得 IP 最直接的方法。若要手動格式化整數形式的 IP,也可以這樣做:
public static String getLocalIpAddress(Context ctx) {
WifiManager wifiManager = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
try {
return InetAddress.getByName(String.format("%d.%d.%d.%d",
(ipAddress & 0xff),
(ipAddress >> 8 & 0xff),
(ipAddress >> 16 & 0xff),
(ipAddress >> 24 & 0xff))).toString();
} catch (UnknownHostException e) {
return null;
}
}
public static String getLocalMacAddress(Context ctx) {
WifiManager wifi = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
return info.getMacAddress();
}
透過 WifiInfo 的 getMacAddress() 就能取得裝置的 MAC 位址。需要注意的是,這些功能都需要在 AndroidManifest.xml 中聲明 ACCESS_WIFI_STATE 等相關權限,而近版本的 Android 對 MAC 位址的取得也設下了更多限制,實作時要特別留意。
一次搞懂 margin 與 padding、layout_gravity 與 gravity 的差別
這幾個屬性在日常開發中幾乎天天用到,但也最容易一時糊塗寫錯。下面用實例把它們的作用範圍徹底分清楚。 一、Layout_Margin 與 padding 1.1 完全不
Android 四大元件終極篇:Service 完整解析(啟動服務、綁定服務與生命週期)
Service 是 Android 四大元件之一,用來在後台執行長時間的操作而不需要使用者介面。典型用途包括網路傳輸、播放音樂、檔案讀寫,或與 ContentProvid
Android L 新控件 RecyclerView 詳解與自製 Demo(多類型混排)
一、官方怎麼介紹 RecyclerView 在 Google 官方文件中,它是這樣被定義的: RecyclerView is a more advanced and fl
Android 開源日誌庫 Logger 使用教學
1. Logger 是什麼 日常開發少不了和 Log 打交道。回想一下我們的典型用法:先定義一個靜態常量 TAG,值通常是當前類的類名,然後在需要的地方呼叫 Log.d(