編輯:關於 Android 程式設計
不廢話,直接上程式碼。獲取 IP 通常分兩種需求:一個是裝置在公網上的出口 IP(外網 IP),一個是裝置在區域網路中的 IP(內網 IP)。
先看外網 IP。思路是訪問一個會回顯 IP 的網址,再用正則表達式把 IP 從返回的頁面中抓出來。注意這個操作涉及網路請求,一定要放到後台線程裡執行:
/**
* 獲取外網的 IP(要訪問 Url,需放到後台線程裡處理)
* @return 外網 IP 字串
*/
public static String GetNetIp() {
URL infoUrl = null;
InputStream inStream = null;
String ipLine = "";
HttpURLConnection httpConnection = null;
try {
infoUrl = new URL("https://ip168.com/");
URLConnection connection = infoUrl.openConnection();
httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
inStream = httpConnection.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inStream, "utf-8"));
StringBuilder strber = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
strber.append(line + "\n");
}
Pattern pattern = Pattern.compile(
"((?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d))))");
Matcher matcher = pattern.matcher(strber.toString());
if (matcher.find()) {
ipLine = matcher.group();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inStream.close();
httpConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return ipLine;
}
再看內網 IP。這就單純多了,只需遍歷所有網路介面,找出第一個非 loopback 的 IPv4 位址即可:
/**
* 獲取本地 IP
* @return 內網 IP 字串
*/
public static String getLocalIpAddress() {
try {
Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
while (en.hasMoreElements()) {
NetworkInterface ni = en.nextElement();
Enumeration<InetAddress> enIp = ni.getInetAddresses();
while (enIp.hasMoreElements()) {
InetAddress inet = enIp.nextElement();
if (!inet.isLoopbackAddress() && (inet instanceof Inet4Address)) {
return inet.getHostAddress().toString();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return "0";
}
ADB 指令入門到實戰:環境配置、裝置連線與日常開發技巧
adb(Android Debug Bridge)這個名字大概每個做 Android 的人都聽過,但真正把它用順手的人並不多。這段時間參與 Android 系統層面的開發
Android 自定義環形進度條實作
自定義屬性在 attrs.xml 宣告 radius、strokeWidth、circleColor、ringColor、textColor、textSize,方便在布局
Android UI 元件:Spinner 下拉列表詳解
Spinner 外觀與屬性 Spinner 是 Android 常見的下拉選擇元件。它可透過 android:entries 直接綁定字串陣列資源,也可在程式碼中用 Ar
Picasso 圖片加載庫詳解:二次封裝 PicassoUtils 打造微信精選
官網:https://square.github.io/picasso/ Picasso(學名畢加索)是 Square 公司開源的一款 Android 圖形緩存庫,使