从 Android 10 开始,应用必须具有 READ_PRIVILEGED_PHONE_STATE 特许权限才能访问设备的不可重置标识符(包含 IMEI 和序列号)。
注意:从 Google Play 商店安装的第三方应用无法声明特许权限。
/** * 读取手机设备信息测试代码 */ public class PhoneInfoUtils { private static TelephonyManager tm; public static String getDeviceId(Context context) { String deviceId; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { deviceId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID); } else { final TelephonyManager mTelephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (context.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { return ""; } } assert mTelephony != null; if (mTelephony.getDeviceId() != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { deviceId = mTelephony.getImei(); }else { deviceId = mTelephony.getDeviceId(); } } else { deviceId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID); } } Log.d("deviceId", deviceId); return deviceId; } /** * 获取屏幕分辨率 * * @return */ public static int[] getMetrics() { WindowManager wm = (WindowManager) MyApp.getAppContext().getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); Point point = new Point(); display.getSize(point); int width = point.x; int height = point.y; int[] metrics = {width, height}; return metrics; } /** * 设备厂商 * * @return */ public static String getPhoneBrand() { return Build.BOARD + " " + Build.MANUFACTURER; } /** * 设备名称 * * @return */ public static String getPhoneModel() { return Build.MODEL; } /** * 设备名称 * * @return */ public static String getAndroidInfo() { return Build.VERSION.RELEASE; } /** * 得到软件版本号 * * @param context 上下文 * @return 当前版本Code */ public static int getVerCode(Context context) { int verCode = -1; try { String packageName = context.getPackageName(); verCode = context.getPackageManager() .getPackageInfo(packageName, 0).versionCode; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return verCode; } /** * 获得APP名称 * * @param context * @return */ 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; } }