Domanda

Per identificare ciascun dispositivo in modo univoco, vorrei utilizzare l'IMEI (o il numero ESN per i dispositivi CDMA).Come accedervi a livello di programmazione?

È stato utile?

Soluzione

Si desidera chiamare android.telephony.TelephonyManager.getDeviceId() .

Ciò restituirà qualsiasi stringa identifica univocamente il dispositivo (IMEI su GSM, MEID per CDMA).

È necessario l'autorizzazione seguente nella vostra AndroidManifest.xml:

<uses-permission android:name="android.permission.READ_PHONE_STATE" />

al fine di fare questo.

Detto questo, fare attenzione a fare questo. Non solo gli utenti si chiedono perché l'applicazione sta accedendo loro stack di telefonia, potrebbe essere difficile per migrare i dati sopra se l'utente riceve un nuovo dispositivo.

Aggiornamento: Come accennato nei commenti qui sotto, questo non è un modo sicuro per autenticare gli utenti, e solleva problemi di privacy. Non è raccomandato. Invece, guarda il Google+ Accesso API se si desidera implementare un attrito sistema di login.

Il Android API Backup è disponibile anche se si desidera solo un modo leggero persistere un fascio di corde per quando un utente ripristina il loro telefono (o acquista un nuovo dispositivo).

Altri suggerimenti

In aggiunta alla risposta di Trevor Johns, è possibile utilizzare questo come segue:

TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.getDeviceId();

E si dovrebbe aggiungere la seguente autorizzazione nel file Manifest.xml:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

In emulatore, probabilmente otterrete un come un "00000 ..." valore. GetDeviceID () restituisce NULL se l'ID del dispositivo non è disponibile.

Io uso il seguente codice per ottenere il codice IMEI o utilizzare Secure.ANDROID_ID in alternativa, quando il dispositivo non dispone di funzionalità di telefono:

/**
 * 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;
}

In alternativa, è possibile utilizzare l'impostazione da Android.Provider.Settings.System (come descritto qui strazerre ANDROID_ID. it ).

Questo ha il vantaggio che non richiede permessi speciali, ma può cambiare se un'altra applicazione ha accesso in scrittura e lo cambia (che è apparentemente insolito ma non impossibile).

Solo per riferimento qui è il codice dal blog:

import android.provider.Settings;
import android.provider.Settings.System;   

String androidID = System.getString(this.getContentResolver(),Secure.ANDROID_ID);

Nota Attuazione : se l'ID è fondamentale per l'architettura del sistema è necessario essere consapevoli del fatto che, in pratica, alcuni dei fine bassa telefoni e tablet Android sono stati trovati riutilizzare lo stesso ANDROID_ID (9774d56d682e549c era il valore che mostra nei nostri log)

Da: http : //mytechead.wordpress.com/2011/08/28/how-to-get-imei-number-of-android-device/ :

Il codice seguente aiuta ad ottenere il numero IMEI di dispositivi Android:

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String device_id = tm.getDeviceId();

Autorizzazioni necessarie in Android Manifest:

android.permission.READ_PHONE_STATE

NOTA: Nel caso di compresse o dispositivi che non può agire come Telefono Cellulare IMEI sarà nullo.

per ottenere IMEI (identificatore apparecchiature mobile internazionale)

public String getIMEI(Activity activity) {
    TelephonyManager telephonyManager = (TelephonyManager) activity
            .getSystemService(Context.TELEPHONY_SERVICE);
    return telephonyManager.getDeviceId();
}

per ottenere dispositivo unico id

public String getDeviceUniqueID(Activity activity){
    String device_unique_id = Secure.getString(activity.getContentResolver(),
            Secure.ANDROID_ID);
    return device_unique_id;
}

Per Android 6.0 e versioni successive il gioco è cambiato in modo che io suggerisco di usare questo;

Il modo migliore per andare è durante il runtime altro si ottiene errori di autorizzazione.

   /**
 * 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);
}
}

Spero che questo voi o qualcuno aiuta.

Nuovo aggiornamento:

Per Android versione 6 e successive, l'indirizzo MAC WLAN è stato deprecato, segui la risposta di Trevor Johns

Aggiornamento:

Per l'identificazione univoca dei dispositivi, è possibile utilizzare Sicuro.ANDROID_ID.

Vecchia risposta:

Svantaggi dell'utilizzo dell'IMEI come ID dispositivo univoco:

  • L'IMEI dipende dallo slot Simcard del dispositivo, quindi non lo è possibile ottenere l'IMEI per i dispositivi che non utilizzano Simcard.Nei dispositivi Dual SIM, otteniamo 2 IMEI diversi per lo stesso dispositivo poiché ha 2 slot per la scheda SIM.

È possibile utilizzare la stringa dell'indirizzo MAC WLAN (non consigliato per Marshmallow e Marshmallow+ poiché l'indirizzo MAC WLAN è stato deprecato su Marshmallow forward.Quindi otterrai un valore fasullo)

Possiamo ottenere l'ID univoco per i telefoni Android anche utilizzando l'indirizzo MAC WLAN.L'indirizzo MAC è univoco per tutti i dispositivi e funziona con tutti i tipi di dispositivi.

Vantaggi dell'utilizzo dell'indirizzo MAC WLAN come ID dispositivo:

  • È un identificatore univoco per tutti i tipi di dispositivi (smartphone e tablet).

  • Rimane unico se l'applicazione viene reinstallata

Svantaggi dell'utilizzo dell'indirizzo MAC WLAN come ID dispositivo:

  • Ti danno un valore fasullo da Marshmallow e superiori.

  • Se il dispositivo non dispone di hardware wifi, si ottiene un indirizzo MAC nullo, ma in generale si vede che la maggior parte dei dispositivi Android ha il wifi hardware e non ci sono pochi dispositivi sul mercato senza wifi hardware.

FONTE : technetexperts.com

Come in API 26 GetDeviceID () sono ammortizzati in modo da poter utilizzare il codice seguente per soddisfare API 26 e versioni precedenti

TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String imei="";
if (android.os.Build.VERSION.SDK_INT >= 26) {
  imei=telephonyManager.getImei();
}
else
{
  imei=telephonyManager.getDeviceId();
}

Non dimenticare di aggiungere richiesta di permesso per "READ_PHONE_STATE" da usare sopra il codice.

Il metodo GetDeviceID () del TelephonyManager restituisce l'ID univoco del dispositivo, ad esempio, l'IMEI per GSM e il MEID o ESN per i telefoni CDMA. Restituisce null se l'ID del dispositivo non è disponibile.

del codice 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> 

Permission Required READ_PHONE_STATE nel file manifesto.

È possibile utilizzare questo TelephonyManager TELEPHONY_SERVICE per ottenere unico ID del dispositivo , È richiesta l'autorizzazione: READ_PHONE_STATE

<uses-permission android:name="android.permission.READ_PHONE_STATE" />

Esempio, il IMEI GSM e MEID o ESN per CDMA i telefoni.

/**
 * 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();
}

restituire null se ID dispositivo non è disponibile .

Il metodo getDeviceId() è deprecato. C'è un nuovo metodo per questo getImei(int)

Controlla qui

Usa il codice qui sotto ti dà numero IMEI:

TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
System.out.println("IMEI::" + telephonyManager.getDeviceId());

Prova questo (bisogno di ottenere prima IMEI sempre)

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();
        }

per il livello API 11 o superiore:

case TelephonyManager.PHONE_TYPE_SIP: 
return "SIP";

TelephonyManager tm= (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
textDeviceID.setText(getDeviceID(tm));

Codice Kotlin per ottenere DeviceId (IMEI) con il permesso gestione e di controllo di comparabilità per tutte le versioni di 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

    }

Anche aggiungere questa autorizzazione per AndroidManifest.xml:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/> <!-- IMEI-->

Per chi cerca una versione Kotlin, si può usare qualcosa di simile;

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")
}

Nota: È necessario avvolgere telephonyService() sopra con un controllo delle autorizzazioni utilizzando checkSelfPermission o qualunque metodo utilizzato.

Anche aggiungere questa autorizzazione nel file manifesto;

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top