如何获取 Android 设备 ID java android

how to get Android devices ID java android

如何在 android 12

中获取 android 设备 ID

这是我的代码

   @SuppressLint("HardwareIds") String android_id = Secure.getString(getContext().getContentResolver(),
            Secure.ANDROID_ID);

来自Android Docs

Starting with API level 29, persistent device identifiers are guarded behind additional restrictions, and apps are recommended to use resettable identifiers (see Best practices for unique identifiers). This method can be invoked if one of the following requirements is met:

    If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this is a privileged permission that can only be granted to apps preloaded on the device.
    If the calling app is the device owner of a fully-managed device, a profile owner of an organization-owned device, or their delegates (see DevicePolicyManager.getEnrollmentSpecificId()).
    If the calling app has carrier privileges (see hasCarrierPrivileges()) on any active subscription.
    If the calling app is the default SMS role holder (see RoleManager.isRoleHeld(java.lang.String)).
    If the calling app has been granted the Manifest.permission#USE_ICC_AUTH_WITH_DEVICE_IDENTIFIER permission. 

If the calling app does not meet one of these requirements then this method will behave as follows:

    If the calling app's target SDK is API level 28 or lower and the app has the READ_PHONE_STATE permission then null is returned.
    If the calling app's target SDK is API level 28 or lower and the app does not have the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or higher, then a SecurityException is thrown.


这是我的函数。

@SuppressLint("HardwareIds")
public static String getDeviceId(Context context) {
    return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
}