Pergunta

Para identificar cada dispositivos exclusivamente, gostaria de usar o número IMEI (ou ESN para dispositivos CDMA). Como acessar isso programaticamente?

Foi útil?

Solução

Você quer ligar android.telephony.TelephonyManager.getDeviceId().

Isso retornará qualquer string que identifique exclusivamente o dispositivo (IMEI no GSM, MEID para CDMA).

Você precisará da seguinte permissão em seu AndroidManifest.xml:

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

Para fazer isso.

Dito isto, tenha cuidado ao fazer isso. Os usuários não apenas se perguntam por que seu aplicativo está acessa a pilha de telefonia, mas também pode ser difícil migrar dados se o usuário obtiver um novo dispositivo.

Atualizar: Como mencionado nos comentários abaixo, essa não é uma maneira segura de autenticar usuários e levanta preocupações de privacidade. Não é recomendado. Em vez disso, olhe para o API de login do Google+ Se você deseja implementar um sistema de login sem atrito.

o API de backup do Android Também está disponível se você deseja apenas uma maneira leve de persistir um pacote de strings para quando um usuário redefine o telefone (ou compra um novo dispositivo).

Outras dicas

Além da resposta de Trevor Johns, você pode usar isso da seguinte maneira:

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

E você deve adicionar a seguinte permissão ao seu arquivo manifest.xml:

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

No emulador, você provavelmente obterá um valor "00000 ...". getDeviceId () retorna nulo se o ID do dispositivo não estiver disponível.

Eu uso o código a seguir para obter o IMEI ou usar o seguro.android_id como alternativa, quando o dispositivo não possui recursos de telefone:

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

Ou você pode usar a configuração Android_ID de Android.provider.settings.system (conforme descrito aqui strazerre.com).

Isso tem a vantagem de que não requer permissões especiais, mas pode mudar se outro aplicativo tiver acesso de gravação e alterar -o (o que é aparentemente incomum, mas não impossível).

Apenas para referência aqui é o código do blog:

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

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

Nota de implementação: Se o ID for fundamental para a arquitetura do sistema, você precisa estar ciente de que, na prática, alguns dos telefones e tablets Android muito baixos foram encontrados reutilizando o mesmo Android_ID (9774D56D682E549C foi o valor que aparece em nossos logs)

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

O código a seguir ajuda a obter o número IMEI de dispositivos Android:

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

Permissões necessárias no manifesto do Android:

android.permission.READ_PHONE_STATE

NOTA: No caso de tablets ou dispositivos que não podem atuar como o celular IMEI será nulo.

para obter Imei (Identificador internacional de equipamentos móveis)

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

para obter ID exclusivo do dispositivo

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

Para o Android 6.0+, o jogo mudou, então sugiro que você use isso;

O melhor caminho a percorrer é durante o tempo de execução que você recebe erros de permissão.

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

Espero que isso ajude você ou alguém.

Nova atualização:

Para o Android versão 6 e acima, o endereço da WLAN MAC foi descontinuado, siga Trevor Johns Response

Atualizar:

Para identificação exclusiva de dispositivos, você pode usar Seguro.android_id.

Resposta antiga:

Desvantagens do uso do IMEI como ID de dispositivo exclusivo:

  • O IMEI depende do slot Simcard do dispositivo, portanto, não é possível obter o IMEI para os dispositivos que não usam o SIMCARD. Em dispositivos SIM duplos, obtemos 2 IMEIs diferentes para o mesmo dispositivo que possui 2 slots para o SIMCARD.

Você pode usar a string de endereço WLAN MAC (não recomendada para marshmallow e marshmallow+ como o endereço WLAN MAC foi descontinuado no marshmallow para a frente. Então você receberá um valor falso)

Podemos obter o ID exclusivo para telefones Android usando o endereço WLAN MAC também. O endereço MAC é exclusivo para todos os dispositivos e funciona para todos os tipos de dispositivos.

Vantagens do uso do endereço WLAN MAC como ID do dispositivo:

  • É um identificador exclusivo para todos os tipos de dispositivos (smartphones e tablets).

  • Permanece único se o aplicativo for reinstalado

Desvantagens do uso do endereço WLAN MAC como ID do dispositivo:

  • Dê a você um valor falso do marshmallow e acima.

  • Se o dispositivo não tiver hardware WiFi, você obtém o endereço MAC nulo, mas geralmente é visto que a maioria dos dispositivos Android possui hardware WiFi e quase não há poucos dispositivos no mercado sem hardware WiFi.

FONTE : technetexperts.com

Como na API 26 getDeviceId () é depreciado para que você possa usar o código seguinte para atender a API 26 e versões anteriores

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

Não se esqueça de adicionar a solicitação de permissão para "read_phone_state" usar o código acima.

O método getDeviceId () do TelefonyManager retorna o ID de dispositivo exclusivo, por exemplo, o IMEI para GSM e o MEID ou ESN para telefones CDMA. Retorne nulo se o ID do dispositivo não estiver disponível.

Código 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> 

Permissão necessáriaRead_phone_state no arquivo manifesto.

Você pode usar este manager de telefonia Telefony_service função para obter ID de dispositivo exclusivo, Requer permissão: read_phone_state

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

Exemplo, o IMEI para GSM e a Meid ou ESN para CDMA telefones.

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

Retornar nulo E se O ID do dispositivo não está disponível.

O método getDeviceId() é preterido. Lá um novo método para isso getImei(int)

Verifique aqui

Use o código abaixo fornece o número IMEI:

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

Experimente isso (preciso obter o primeiro 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();
        }

Para o nível 11 ou superior da API:

case TelephonyManager.PHONE_TYPE_SIP: 
return "SIP";

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

Código Kotlin para obter o DeviceID (IMEI) com o tratamento da verificação de permissão e comparabilidade de todas as versões do 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

    }

Adicione também esta permissão ao Androidmanifest.xml:

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

Para quem procura uma versão Kotlin, você pode usar algo assim;

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: você deve embrulhar telephonyService() acima com uma verificação de permissão usando Checkelfishpermission ou qualquer método que você use.

Adicione também essa permissão no arquivo de manifesto;

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top