[英]How to get device's IMEI/ESN number with code programming But in android > 6
[英]How to get the device's IMEI/ESN programmatically in android?
為了唯一識別每個設備,我想使用 IMEI(或 CDMA 設備的 ESN 號)。 如何以編程方式訪問它?
你想調用android.telephony.TelephonyManager.getDeviceId()
。
這將返回唯一標識設備的任何字符串(GSM 上的 IMEI,CDMA 上的 MEID)。
您需要在AndroidManifest.xml
獲得以下權限:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
為了做到這一點。
話雖如此,做這件事要小心。 用戶不僅會想知道為什么您的應用程序要訪問他們的電話堆棧,而且如果用戶獲得新設備,可能難以遷移數據。
更新:正如在下面的評論中提到的,這不是一種對用戶進行身份驗證的安全方式,並且會引起隱私問題。 不推薦。 相反,如果您想實現無摩擦的登錄系統,請查看Google+ 登錄 API 。
如果您只想要一種輕量級的方式來在用戶重置手機(或購買新設備)時保留一組字符串,也可以使用Android Backup API 。
除了 Trevor Johns 的回答之外,您還可以按如下方式使用:
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.getDeviceId();
您應該將以下權限添加到您的 Manifest.xml 文件中:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
在模擬器中,您可能會得到類似“00000...”的值。 如果設備 ID 不可用,則 getDeviceId() 返回 NULL。
當設備沒有電話功能時,我使用以下代碼獲取 IMEI 或使用 Secure.ANDROID_ID 作為替代:
/**
* Returns the unique identifier for the device
*
* @return unique identifier for the device
*/
public String getDeviceIMEI() {
String deviceUniqueIdentifier = null;
TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
if (null != tm) {
deviceUniqueIdentifier = tm.getDeviceId();
}
if (null == deviceUniqueIdentifier || 0 == deviceUniqueIdentifier.length()) {
deviceUniqueIdentifier = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
}
return deviceUniqueIdentifier;
}
或者您可以使用 Android.Provider.Settings.System 中的 ANDROID_ID 設置(如strazerre.com此處所述)。
這樣做的優點是它不需要特殊權限,但可以在另一個應用程序具有寫訪問權限並更改它時進行更改(這顯然不尋常但並非不可能)。
僅供參考,這里是博客中的代碼:
import android.provider.Settings;
import android.provider.Settings.System;
String androidID = System.getString(this.getContentResolver(),Secure.ANDROID_ID);
實施注意事項:如果 ID 對系統架構至關重要,您需要注意在實踐中發現一些非常低端的 Android 手機和平板電腦重復使用相同的 ANDROID_ID(9774d56d682e549c 是我們日志中顯示的值)
來自: http : //mytechead.wordpress.com/2011/08/28/how-to-get-imei-number-of-android-device/ :
以下代碼有助於獲取安卓設備的 IMEI 號碼:
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String device_id = tm.getDeviceId();
Android 清單中所需的權限:
android.permission.READ_PHONE_STATE
注意:如果是平板電腦或不能作為手機的設備,IMEI 將為空。
獲取IMEI (國際移動設備標識符)
public String getIMEI(Activity activity) {
TelephonyManager telephonyManager = (TelephonyManager) activity
.getSystemService(Context.TELEPHONY_SERVICE);
return telephonyManager.getDeviceId();
}
獲取設備唯一ID
public String getDeviceUniqueID(Activity activity){
String device_unique_id = Secure.getString(activity.getContentResolver(),
Secure.ANDROID_ID);
return device_unique_id;
}
對於 Android 6.0+,游戲已經改變,所以我建議你使用它;
最好的方法是在運行時,否則你會遇到權限錯誤。
/**
* A loading screen after AppIntroActivity.
*/
public class LoadingActivity extends BaseActivity {
private static final int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 0;
private TextView loading_tv2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loading);
//trigger 'loadIMEI'
loadIMEI();
/** Fading Transition Effect */
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
/**
* Called when the 'loadIMEI' function is triggered.
*/
public void loadIMEI() {
// Check if the READ_PHONE_STATE permission is already available.
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
// READ_PHONE_STATE permission has not been granted.
requestReadPhoneStatePermission();
} else {
// READ_PHONE_STATE permission is already been granted.
doPermissionGrantedStuffs();
}
}
/**
* Requests the READ_PHONE_STATE permission.
* If the permission has been denied previously, a dialog will prompt the user to grant the
* permission, otherwise it is requested directly.
*/
private void requestReadPhoneStatePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_PHONE_STATE)) {
// Provide an additional rationale to the user if the permission was not granted
// and the user would benefit from additional context for the use of the permission.
// For example if the user has previously denied the permission.
new AlertDialog.Builder(LoadingActivity.this)
.setTitle("Permission Request")
.setMessage(getString(R.string.permission_read_phone_state_rationale))
.setCancelable(false)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//re-request
ActivityCompat.requestPermissions(LoadingActivity.this,
new String[]{Manifest.permission.READ_PHONE_STATE},
MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
}
})
.setIcon(R.drawable.onlinlinew_warning_sign)
.show();
} else {
// READ_PHONE_STATE permission has not been granted yet. Request it directly.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE},
MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
}
}
/**
* Callback received when a permissions request has been completed.
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == MY_PERMISSIONS_REQUEST_READ_PHONE_STATE) {
// Received permission result for READ_PHONE_STATE permission.est.");
// Check if the only required permission has been granted
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// READ_PHONE_STATE permission has been granted, proceed with displaying IMEI Number
//alertAlert(getString(R.string.permision_available_read_phone_state));
doPermissionGrantedStuffs();
} else {
alertAlert(getString(R.string.permissions_not_granted_read_phone_state));
}
}
}
private void alertAlert(String msg) {
new AlertDialog.Builder(LoadingActivity.this)
.setTitle("Permission Request")
.setMessage(msg)
.setCancelable(false)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do somthing here
}
})
.setIcon(R.drawable.onlinlinew_warning_sign)
.show();
}
public void doPermissionGrantedStuffs() {
//Have an object of TelephonyManager
TelephonyManager tm =(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
//Get IMEI Number of Phone //////////////// for this example i only need the IMEI
String IMEINumber=tm.getDeviceId();
/************************************************
* **********************************************
* This is just an icing on the cake
* the following are other children of TELEPHONY_SERVICE
*
//Get Subscriber ID
String subscriberID=tm.getDeviceId();
//Get SIM Serial Number
String SIMSerialNumber=tm.getSimSerialNumber();
//Get Network Country ISO Code
String networkCountryISO=tm.getNetworkCountryIso();
//Get SIM Country ISO Code
String SIMCountryISO=tm.getSimCountryIso();
//Get the device software version
String softwareVersion=tm.getDeviceSoftwareVersion()
//Get the Voice mail number
String voiceMailNumber=tm.getVoiceMailNumber();
//Get the Phone Type CDMA/GSM/NONE
int phoneType=tm.getPhoneType();
switch (phoneType)
{
case (TelephonyManager.PHONE_TYPE_CDMA):
// your code
break;
case (TelephonyManager.PHONE_TYPE_GSM)
// your code
break;
case (TelephonyManager.PHONE_TYPE_NONE):
// your code
break;
}
//Find whether the Phone is in Roaming, returns true if in roaming
boolean isRoaming=tm.isNetworkRoaming();
if(isRoaming)
phoneDetails+="\nIs In Roaming : "+"YES";
else
phoneDetails+="\nIs In Roaming : "+"NO";
//Get the SIM state
int SIMState=tm.getSimState();
switch(SIMState)
{
case TelephonyManager.SIM_STATE_ABSENT :
// your code
break;
case TelephonyManager.SIM_STATE_NETWORK_LOCKED :
// your code
break;
case TelephonyManager.SIM_STATE_PIN_REQUIRED :
// your code
break;
case TelephonyManager.SIM_STATE_PUK_REQUIRED :
// your code
break;
case TelephonyManager.SIM_STATE_READY :
// your code
break;
case TelephonyManager.SIM_STATE_UNKNOWN :
// your code
break;
}
*/
// Now read the desired content to a textview.
loading_tv2 = (TextView) findViewById(R.id.loading_tv2);
loading_tv2.setText(IMEINumber);
}
}
希望這對您或某人有幫助。
新更新:
對於 Android 6 及以上版本,WLAN MAC 地址已被棄用,請參考 Trevor Johns 的回答
更新:
對於設備的唯一標識,您可以使用Secure.ANDROID_ID 。
舊答案:
使用 IMEI 作為唯一設備 ID 的缺點:
您可以使用 WLAN MAC 地址字符串(不推薦用於 Marshmallow 和 Marshmallow+,因為 WLAN MAC 地址已在 Marshmallow forward 上棄用。因此您會得到一個虛假值)
我們也可以使用 WLAN MAC 地址獲取安卓手機的唯一 ID。 MAC 地址對所有設備都是唯一的,它適用於所有類型的設備。
使用 WLAN MAC 地址作為 Device ID 的優點:
它是所有類型設備(智能手機和平板電腦)的唯一標識符。
如果重新安裝應用程序,它仍然是唯一的
使用 WLAN MAC 地址作為 Device ID 的缺點:
給你一個來自棉花糖及以上的虛假價值。
如果設備沒有wifi硬件,那么你會得到空的MAC地址,但通常可以看到大多數Android設備都有wifi硬件,市場上幾乎沒有沒有wifi硬件的設備。
由於在 API 26 中getDeviceId()
已折舊,因此您可以使用以下代碼來滿足 API 26 和更早版本
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String imei="";
if (android.os.Build.VERSION.SDK_INT >= 26) {
imei=telephonyManager.getImei();
}
else
{
imei=telephonyManager.getDeviceId();
}
不要忘記為READ_PHONE_STATE
添加權限請求以使用上述代碼。
更新:從 Android 10 開始,用戶應用程序無法獲取不可重置的硬件標識符(如 IMEI)。
TelephonyManager 的 getDeviceId() 方法返回唯一的設備 ID,例如,GSM 的 IMEI 和 CDMA 電話的 MEID 或 ESN。 如果設備 ID 不可用,則返回 null。
Java代碼
package com.AndroidTelephonyManager;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.widget.TextView;
public class AndroidTelephonyManager extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView textDeviceID = (TextView)findViewById(R.id.deviceid);
//retrieve a reference to an instance of TelephonyManager
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
textDeviceID.setText(getDeviceID(telephonyManager));
}
String getDeviceID(TelephonyManager phonyManager){
String id = phonyManager.getDeviceId();
if (id == null){
id = "not available";
}
int phoneType = phonyManager.getPhoneType();
switch(phoneType){
case TelephonyManager.PHONE_TYPE_NONE:
return "NONE: " + id;
case TelephonyManager.PHONE_TYPE_GSM:
return "GSM: IMEI=" + id;
case TelephonyManager.PHONE_TYPE_CDMA:
return "CDMA: MEID/ESN=" + id;
/*
* for API Level 11 or above
* case TelephonyManager.PHONE_TYPE_SIP:
* return "SIP";
*/
default:
return "UNKNOWN: ID=" + id;
}
}
}
XML
<linearlayout android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">
<textview android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="@string/hello">
<textview android:id="@+id/deviceid" android:layout_height="wrap_content" android:layout_width="fill_parent">
</textview></textview></linearlayout>
清單文件中需要READ_PHONE_STATE權限。
您可以使用此 TelephonyManager TELEPHONY_SERVICE函數來獲取唯一的設備 ID ,需要權限:READ_PHONE_STATE
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
例如, GSM的IMEI和CDMA手機的MEID 或 ESN 。
/**
* Gets the device unique id called IMEI. Sometimes, this returns 00000000000000000 for the
* rooted devices.
**/
public static String getDeviceImei(Context ctx) {
TelephonyManager telephonyManager = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
return telephonyManager.getDeviceId();
}
如果設備 ID 不可用,則返回 null 。
試試這個(總是需要先獲得 IMEI)
TelephonyManager mTelephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(LoginActivity.this,Manifest.permission.READ_PHONE_STATE)!= PackageManager.PERMISSION_GRANTED) {
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (mTelephony.getPhoneCount() == 2) {
IME = mTelephony.getImei(0);
}else{
IME = mTelephony.getImei();
}
}else{
if (mTelephony.getPhoneCount() == 2) {
IME = mTelephony.getDeviceId(0);
} else {
IME = mTelephony.getDeviceId();
}
}
} else {
IME = mTelephony.getDeviceId();
}
使用以下代碼為您提供 IMEI 號碼:
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
System.out.println("IMEI::" + telephonyManager.getDeviceId());
不推薦使用getDeviceId()
方法。 這個getImei(int)
有一個新方法
對於 API 級別 11 或更高級別:
case TelephonyManager.PHONE_TYPE_SIP:
return "SIP";
TelephonyManager tm= (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
textDeviceID.setText(getDeviceID(tm));
用於獲取 DeviceId (IMEI) 的 Kotlin 代碼以及所有 android 版本的處理權限和可比性檢查:
val telephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
== PackageManager.PERMISSION_GRANTED) {
// Permission is granted
val imei : String? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) telephonyManager.imei
// older OS versions
else telephonyManager.deviceId
imei?.let {
Log.i("Log", "DeviceId=$it" )
}
} else { // Permission is not granted
}
還要將此權限添加到 AndroidManifest.xml :
<uses-permission android:name="android.permission.READ_PHONE_STATE"/> <!-- IMEI-->
您需要在 AndroidManifest.xml 中獲得以下權限:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
要獲取IMEI (國際移動設備標識符),如果它高於 API 級別 26,那么我們將telephonyManager.getImei()
獲取為 null,為此,我們使用ANDROID_ID作為唯一標識符。
public static String getIMEINumber(@NonNull final Context context)
throws SecurityException, NullPointerException {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String imei;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
assert tm != null;
imei = tm.getImei();
//this change is for Android 10 as per security concern it will not provide the imei number.
if (imei == null) {
imei = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
}
} else {
assert tm != null;
if (tm.getDeviceId() != null && !tm.getDeviceId().equals("000000000000000")) {
imei = tm.getDeviceId();
} else {
imei = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
}
}
return imei;
}
使用以下代碼:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String[] permissions = {Manifest.permission.READ_PHONE_STATE};
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(permissions, READ_PHONE_STATE);
}
} else {
try {
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
return;
}
String imei = telephonyManager.getDeviceId();
} catch (Exception e) {
e.printStackTrace();
}
}
並調用 onRequestPermissionsResult 方法以下代碼:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case READ_PHONE_STATE:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED)
try {
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
return;
}
String imei = telephonyManager.getDeviceId();
} catch (Exception e) {
e.printStackTrace();
}
}
}
在您的 AndroidManifest.xml 中添加以下權限:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
您無法從安卓 10+ 或 29+ 手機中獲取 imei 號碼,這里是用於為設備創建 imei 號碼的替代功能。
public static String getDeviceID(){
String devIDShort = "35" + //we make this look like a valid IMEI
Build.BOARD.length()%10+ Build.BRAND.length()%10 +
Build.CPU_ABI.length()%10 + Build.DEVICE.length()%10 +
Build.DISPLAY.length()%10 + Build.HOST.length()%10 +
Build.ID.length()%10 + Build.MANUFACTURER.length()%10 +
Build.MODEL.length()%10 + Build.PRODUCT.length()%10 +
Build.TAGS.length()%10 + Build.TYPE.length()%10 +
Build.USER.length()%10 ; //13 digits
return devIDShort;
}
對於那些尋找 Kotlin 版本的人,你可以使用這樣的東西;
private fun telephonyService() {
val telephonyManager = getSystemService(TELEPHONY_SERVICE) as TelephonyManager
val imei = if (android.os.Build.VERSION.SDK_INT >= 26) {
Timber.i("Phone >= 26 IMEI")
telephonyManager.imei
} else {
Timber.i("Phone IMEI < 26")
telephonyManager.deviceId
}
Timber.i("Phone IMEI $imei")
}
注意:您必須使用checkSelfPermission或您使用的任何方法通過權限檢查將上面的telephonyService()
包裝起來。
還要在清單文件中添加此權限;
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
對於 Android 10 以下代碼對我有用。
val uid: String = Settings.Secure.getString(ctx.applicationContext.contentResolver, Settings.Secure.ANDROID_ID)
if (ContextCompat.checkSelfPermission(ctx, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
imei = when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> {
uid
}
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
telephonyManager.imei
}
else -> {
telephonyManager.deviceId
}
}
}
對不可重置設備標識符的限制
從 Android 10 開始,應用必須具有READ_PRIVILEGED_PHONE_STATE
特權才能訪問設備的不可重置標識符,包括 IMEI 和序列號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.