Method 1
import android.provider.Settings.Secure;
private String android_id = Secure.getString(getContext().getContentResolver(),
Secure.ANDROID_ID);
There were problems such as changing the number after resetting the factory, but the more the latest version of Android comes, the more the problem is solved, so I recommend doing it as above.
Method 2
If you use Secure.ANDROID_ID
and it works well on the latest phone, but there may be problems with phones with low Android versions, so if you need to support the old version, the following method is recommended.
final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
final String tmDevice, tmSerial, androidId;
tmDevice = "" + tm.GetDeviceId(); //null may appear.
tmSerial = "" + tm.getSimSerialNumber(); // uniq is not guaranteed.
androidId = "" + android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
String deviceId = deviceUuid.toString();
The following permissions must be added to the manifest file in order for the above code to work.
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
Because the values provided by Android hardware alone cannot guarantee unique values, we recommend that you make them like above and save them somewhere to read them.
© 2024 OneMinuteCode. All rights reserved.