編輯:關於 Android 程式設計
開發時經常需要讀取一些裝置層級的資訊,做為版面適配、行為判斷或資料上報的依據。以下把常用的幾類整理成可直接複用的片段。
一、螢幕解析度
能直接拿到 Activity 時:
Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int width = size.x; int height = size.y;
或者使用 DisplayMetrics:
DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); int width = metrics.widthPixels; int height = metrics.heightPixels;
若手上只有 Context 而拿不到 Activity,改用 WindowManager 即可:
WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); Point point = new Point(); display.getSize(point); int width = point.x; int height = point.y;
二、螢幕物理尺寸(英吋)
用解析度除以 DPI 換算成英吋,再取對角線長度:
DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int width = dm.widthPixels; int height = dm.heightPixels; int dens = dm.densityDpi; double wi = (double)width / (double)dens; double hi = (double)height / (double)dens; double x = Math.pow(wi, 2); double y = Math.pow(hi, 2); double screenInches = Math.sqrt(x + y);
這段同樣需要 Activity 才能執行。
三、取得應用程式名稱
public static String getAppName(Context context) {
String appName = "";
try {
PackageManager packageManager = context.getPackageManager();
ApplicationInfo applicationInfo =
packageManager.getApplicationInfo(context.getPackageName(), 0);
appName = (String) packageManager.getApplicationLabel(applicationInfo);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return appName;
}
四、機型與廠商
// 設備廠商 String brand = Build.BRAND; // 設備名稱 String model = Build.MODEL;
五、DeviceID、SIM 卡序號與 IMSI
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); String deviceId = tm.getDeviceId(); String sim = tm.getSimSerialNumber(); String imsi = tm.getSubscriberId();
這幾個 API 需要在 AndroidManifest 中宣告權限:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
值得一提的是,從 Android 10 開始,這類可識別裝置的識別碼已大幅受限,一般應用能拿到的多半是空值或經過遮罩的字串,實際專案上不宜再依賴它做唯一識別。
六、判斷網路類型
public static String getAPNType(Context context) {
String netType = "nono_connect";
// 取得手機所有連接管理物件
ConnectivityManager manager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
// NetworkInfo 為空代表沒有網路
if (networkInfo == null) {
return netType;
}
int nType = networkInfo.getType();
if (nType == ConnectivityManager.TYPE_WIFI) {
netType = "wifi";
} else if (nType == ConnectivityManager.TYPE_MOBILE) {
int nSubType = networkInfo.getSubtype();
TelephonyManager telephonyManager =
(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (nSubType == TelephonyManager.NETWORK_TYPE_LTE
&& !telephonyManager.isNetworkRoaming()) {
netType = "4G";
} else if (nSubType == TelephonyManager.NETWORK_TYPE_UMTS
|| nSubType == TelephonyManager.NETWORK_TYPE_HSDPA
|| (nSubType == TelephonyManager.NETWORK_TYPE_EVDO_0
&& !telephonyManager.isNetworkRoaming())) {
netType = "3G";
} else if (nSubType == TelephonyManager.NETWORK_TYPE_GPRS
|| nSubType == TelephonyManager.NETWORK_TYPE_EDGE
|| (nSubType == TelephonyManager.NETWORK_TYPE_CDMA
&& !telephonyManager.isNetworkRoaming())) {
// 2G:移動與聯通的 2G 為 GPRS 或 EDGE,電信的 2G 為 CDMA
netType = "2G";
} else {
netType = "2G";
}
}
return netType;
}
這裡要注意運算子的優先順序:原本寫法中 && 的優先度高於 ||,容易讓條件判斷不如預期,實務上建議一律補上括號。此外 NetworkInfo 這套 API 在較新版本已被標記為不建議使用,新專案可改用 NetworkCapabilities 搭配 ConnectivityManager 查詢。
七、判斷裝置是否已 Root(不彈出授權視窗)
網路上的判斷方式很多,但有些會跳出要求授權的提示框。以下這種做法只檢查 su 是否存在並具備執行權限,不會觸發彈窗:
/** 判斷手機是否 root,不彈出 root 請求框 */
public static boolean isRoot() {
String binPath = "/system/bin/su";
String xBinPath = "/system/xbin/su";
if (new File(binPath).exists() && isExecutable(binPath)) return true;
if (new File(xBinPath).exists() && isExecutable(xBinPath)) return true;
return false;
}
private static boolean isExecutable(String filePath) {
Process p = null;
try {
p = Runtime.getRuntime().exec("ls -l " + filePath);
// 取得返回內容
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String str = in.readLine();
if (str != null && str.length() >= 4) {
char flag = str.charAt(3);
if (flag == 's' || flag == 'x') return true;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (p != null) {
p.destroy();
}
}
return false;
}
小結
這幾段程式碼的共同前提是:需要權限的 API 一定要記得在 AndroidManifest 宣告,否則會直接收到 SecurityException;而涉及隱私的識別碼,越新的系統版本限制越嚴格,設計時最好預留降級方案。有任何想法歡迎留言交流。
Camera API2 中 CameraMetadata 的參數交互機制解析
在全新的 Camera API2 架構下,不少人會疑惑:那些熟悉的 setParameter/Parameters 怎麼不見了?取而代之的是一套全新的 CameraMet
Android 源碼解析:setContentView() 背後系統做了什麼
前言 在 Activity 中,我們幾乎都會在第一行調用 setContentView(R.layout.XXX),但這行代碼背後系統究竟做了哪些工作?要理解這一點,需要
Android:NineGridLayout — 仿微信朋友圈與 QQ 空間的九宮格圖片展示自定義控件
NineGridLayout 是一個用於展示多圖片的 Android 自定義控件,常見於朋友圈、動態列表、評論區等場景。它能夠根據圖片數量自動調整排列方式,並支持單圖自定
深入Volley源碼:一次網絡請求的完整生命週期剖析
前言 做過Android網絡開發的人,對Volley應該都不會感到陌生。它輕巧、易用,往往只需寥寥幾行代碼就能完成一次網絡請求。但我們真的了解它嗎?Volley內部究竟是