2017-03-27 80 views
0

我想獲取我的android設備的UUID,所以我嘗試使用TelephonyManager.getDeviceId()方法獲取UUID。但它返回的設備ID只有0(如000000000000)。爲什麼TelephonyManager.getDeviceId()返回僅由零作出的設備ID?

這是我的代碼。許多代碼行用於獲取用戶權限READ_PHONE_STATE。

公共類MainActivity擴展AppCompatActivity {

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    TextView tv = (TextView)findViewById(R.id.textview); 

    if(Build.VERSION.SDK_INT == Build.VERSION_CODES.M){ 
     int permissionResult = checkSelfPermission(Manifest.permission.READ_PHONE_STATE); 
     if(permissionResult == PackageManager.PERMISSION_DENIED){ 
      if(shouldShowRequestPermissionRationale(Manifest.permission.READ_PHONE_STATE)) { 
       AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this); 
       dialog.setTitle("Need Permission") 
         .setMessage("This needs to READ_PHONE_STATE Permission. Continue?") 
         .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
          @Override 
          public void onClick(DialogInterface dialog, int which) { 
           if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
            requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, 1000); 
           } 
          } 
         }) 
         .setNegativeButton("No", new DialogInterface.OnClickListener() { 
          @Override 
          public void onClick(DialogInterface dialog, int which) { 
           Toast.makeText(MainActivity.this, "Canceled", Toast.LENGTH_LONG).show(); 
          } 
         }) 
         .create() 
         .show(); 
      } 
      else{ 
       requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, 1000); 
      } 
     } 
     else{ 
      tv.setText(GetDeviceUUID(getBaseContext())); 
     } 
    } 
    tv.setText(GetDeviceUUID(getBaseContext())); 
} 

public static String GetDeviceUUID(Context mContext){ 
    */ 
    TelephonyManager mgr = (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE); 
    final String ID = mgr.getDeviceId(); 
    return ID; 
} 

@Override 
public Context getBaseContext() { 
    return super.getBaseContext(); 
} 

}

+0

你在模擬器上運行嗎? – Ragini

+0

getDeviceId()返回唯一的設備ID,例如GSM的IMEI和CDMA手機的MEID或ESN。如果設備ID不可用,則返回null。 這是getDeviceID()方法的行爲,但我想知道是在模擬器上測試應用程序嗎? –

+0

感謝您的幫助。是的,我在模擬器上測試:) – MagmaTart

回答

0

是,對模擬器的仿真器不具備IMEI號返回0。 使用它來生成設備ID:

final String tmDevice, tmSerial, androidId; 
       tmDevice = "" + tm.getDeviceId(); 
       tmSerial = "" + tm.getSimSerialNumber(); 
       androidId = "" + android.provider.Settings.Secure.getString(getAppContext().getContentResolver(), 
         android.provider.Settings.Secure.ANDROID_ID); 

       UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode()); 

這會給你一個唯一的設備ID。

相關問題