Android设备IMEI获取问题(getdeviceid()已废弃)及Runtime Permission使用咨询
Hey there! Let's break down your two Android questions clearly—these are super common pain points, so I’ve got you covered.
First off, let's unpack why getDeviceId() isn't working for you:
Starting with Android 10 (API 29), getDeviceId() was officially deprecated due to privacy restrictions. On top of that, for Android 6.0+ (API 23) devices, you need to request the READ_PHONE_STATE permission dynamically (we’ll cover this in the second question) before accessing any device identifier methods—this is exactly why it failed on your Android 6.0 device.
Here’s how to handle it based on different Android versions:
Android 6.0 to Android 9 (API 23–28)
- Make sure you’ve requested the
READ_PHONE_STATEruntime permission first. - Use
TelephonyManager.getImei()instead ofgetDeviceId(). Remember to handleNullPointerException(for devices without cellular modules, like Wi-Fi-only tablets):TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) { String imei = telephonyManager.getImei(); // Use the IMEI here }
- Make sure you’ve requested the
Android 10+ (API 29 and above)
Regular apps can no longer access IMEI directly—Google tightened privacy rules to protect user data. Only system apps or apps with the specialREAD_PRIVILEGED_PHONE_STATEpermission (restricted to system-level apps) can usegetImei(). For regular apps, use these reliable alternatives:Settings.Secure.ANDROID_ID: A 64-bit string generated when the device first boots. It stays consistent unless the user factory resets the device, though some manufacturers may change it during system updates.String androidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);- Custom UUID: Generate a unique UUID when your app first launches, then store it in
SharedPreferencesor a local file. This stays consistent across app updates but resets if the user uninstalls/reinstalls the app:String uniqueId = UUID.randomUUID().toString(); // Store this in SharedPreferences for future use
Android 6.0 introduced runtime permissions for dangerous permissions (like READ_PHONE_STATE, CAMERA, ACCESS_FINE_LOCATION)—these can’t just be declared in the manifest; you need to ask the user for permission at runtime. Here’s the step-by-step process:
Declare the permission in
AndroidManifest.xml
First, add the permission to your manifest (this is still required even for runtime permissions):<uses-permission android:name="android.permission.READ_PHONE_STATE" />Check if the permission is already granted
Before performing any action that requires the permission, check if it’s already been granted:int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE); if (permissionCheck != PackageManager.PERMISSION_GRANTED) { // Permission not granted—request it from the user } else { // Permission granted—proceed with your task (like getting IMEI) }Request the permission from the user
If the permission isn’t granted, callrequestPermissions()to show the system’s permission dialog:// Define a unique request code (any integer works) private static final int REQUEST_PHONE_STATE = 101; ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_PHONE_STATE);Handle the permission result
Override theonRequestPermissionsResult()method to check if the user granted or denied the permission:@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_PHONE_STATE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission granted—now you can access the IMEI or other restricted data TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); String imei = telephonyManager.getImei(); } else { // Permission denied—show a message explaining why you need it, or offer an alternative workflow Toast.makeText(this, "Permission needed to access device information", Toast.LENGTH_SHORT).show(); } } }For Android 11+ (API 30): If the user denies the permission twice, the system won’t show the dialog again. In this case, you should redirect them to your app’s settings page to enable it manually:
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", getPackageName(), null); intent.setData(uri); startActivity(intent);
内容的提问来源于stack exchange,提问作者Somoud




