각 장치를 고유하게 식별하기 위해 IMEI (또는 CDMA 장치의 경우 ESN 번호)를 사용하고 싶습니다. 프로그래밍 방식으로 액세스하는 방법은 무엇입니까?
답변
에 전화하고 싶습니다 android.telephony.TelephonyManager.getDeviceId()
.
이것은 장치를 고유하게 식별하는 모든 문자열을 반환합니다 (GSM의 IMEI, CDMA의 경우 MEID).
귀하는 다음과 같은 권한이 필요합니다 AndroidManifest.xml
.
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
이를 위해.
즉,이 작업에주의하십시오. 사용자가 애플리케이션이 전화 통신 스택에 액세스하는 이유를 궁금해 할뿐만 아니라 사용자가 새 장치를 얻는 경우 데이터를 마이그레이션하기 어려울 수 있습니다.
업데이트 : 아래 의견에서 언급했듯이 이는 사용자를 안전하게 보호 할 수있는 방법이 아니며 개인 정보 보호 문제를 제기합니다. 권장하지 않습니다. 마찰이없는 로그인 시스템을 구현 하려면 Google+ 로그인 API를 확인하십시오.
안드로이드 백업 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_ID를 재사용하는 것으로 나타났습니다 (9774d56d682e549c는 로그에 표시되는 값임)
답변
보낸 사람 : http://mytechead.wordpress.com/2011/08/28/how-to-get-imei-number-of-android-device/ :
다음 코드는 IMEI 수의 Android 장치를 얻는 데 도움이됩니다.
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String device_id = tm.getDeviceId();
Android Manifest에 필요한 권한 :
android.permission.READ_PHONE_STATE
참고 : 휴대폰 IMEI로 작동 할 수없는 태블릿 또는 장치의 경우 null이됩니다.
답변
IMEI (International Mobile Equipment Identifier) 를 얻는 방법
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);
}
}
이것이 당신이나 누군가를 돕기를 바랍니다.