Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 中如何取得 IMEI 號

編輯:關於 Android 程式設計

IMEI(International Mobile Equipment Identity,國際移動設備識別碼)是唯一標識行動電話硬體的碼。在單卡設計中,一支手機對應一個 IMEI;雙卡設計中,則是「一張卡一個 IMEI」。取得 IMEI 有兩種情境,做法完全不同。

一、在 Telephony Framework 內部(平台開發)

如果你是在改動 Android 系統原始碼、於 framework 層級取值,可以直接使用 GSMPhone 或 GeminiPhone 提供的介面。要注意的是,KitKat(KK)前後的 API 有明顯差異。

KK 之前的版本

可用介面:

  • GSMPhone.java 中的 getDeviceId()
  • GeminiPhone.java 中的 getDeviceId() 與 getDeviceIdGemini()
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.gemini.GeminiPhone;
import com.android.internal.telephony.PhoneFactory;

Phone phone = PhoneFactory.getDefaultPhone();
String imei = ((GeminiPhone) phone).getDeviceId();

GeminiPhone mGeminiPhone;
String imei_sim1 = mGeminiPhone.getDeviceIdGemini(PhoneConstants.GEMINI_SIM_1);
String imei_sim2 = mGeminiPhone.getDeviceIdGemini(PhoneConstants.GEMINI_SIM_2);

KK 版本上的變化

GeminiPhone 中的 getDeviceIdGemini() 已被移除,而 getDeviceId() 只會回傳 default phone 的 IMEI。因此要取得雙卡各自的 IMEI,必須先定位到對應的 SIM 再取值:

GeminiPhone mGeminiPhone;
String imei_sim1 = mGeminiPhone.getPhonebyId(PhoneConstants.GEMINI_SIM_1).getDeviceId();
String imei_sim2 = mGeminiPhone.getPhonebyId(PhoneConstants.GEMINI_SIM_2).getDeviceId();

二、在一般 App(第三方 APK)中

如果你只是在寫一般的應用程式,請使用 TelephonyManager 的 getDeviceId();雙卡機型則使用 TelephonyManagerEx(雙卡介面)的 getDeviceId(int simId)。

取得預設卡的 IMEI

import android.telephony.TelephonyManager;

String imei = TelephonyManager.getDeviceId();

雙卡介面

import android.telephony.TelephonyManagerEx;

String imei_sim1 = TelephonyManagerEx.getDeviceId(PhoneConstants.GEMINI_SIM_1);
String imei_sim2 = TelephonyManagerEx.getDeviceId(PhoneConstants.GEMINI_SIM_2);

權限與合規提醒

讀取 IMEI 需要 android.permission.READ_PHONE_STATE 權限,在 Android 6.0 以上還必須執行期動態申請。另外要特別注意:TelephonyManagerEx 與 com.android.internal.* 屬於非公開 API,第三方 App 使用它們在跨版本與不同廠商 ROM 上很可能失效,甚至在新版系統上因隱藏 API 限制而無法呼叫。若目的只是裝置識別,建議改用其他方案並取得使用者同意;IMEI 屬於敏感資訊,蒐集與使用需符合相關法規與平台政策。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved