获取UUID Android

时间:2017-03-08 13:29:18

标签: java android uuid

我有UUID Android的问题。这个方法获取UUID Android并添加权限清单

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

此方法获取UUID

   public String deviceUDID(Context ctx) {
        final TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);

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

        UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
        String deviceId = deviceUuid.toString();
        Log.d("Device Id", deviceId);
        return deviceId;
    }

单击带有showView UUID上的show的按钮时,app停止。

我的错误日志

03-08 14:22:39.496 20825-20825/com.novum.smrtkarta E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.xxxx.smrtkarta, PID: 20825
java.lang.SecurityException: getDeviceId: Neither user 10155 nor current process has android.permission.READ_PHONE_STATE.
at android.os.Parcel.readException(Parcel.java:1620)
at android.os.Parcel.readException(Parcel.java:1573)
at com.android.internal.telephony.ITelephony$Stub$Proxy.getDeviceId(ITelephony.java:4207)
at android.telephony.TelephonyManager.getDeviceId(TelephonyManager.java:706)
at com.novum.smrtkarta.activity.GetNumberActivity.deviceUDID(GetNumberActivity.java:81)
at com.novum.smrtkarta.activity.GetNumberActivity$1.onClick(GetNumberActivity.java:62)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

1 个答案:

答案 0 :(得分:1)

您必须确保您的请求获得您的清单READ_PHONE_STATE的许可:

<manifest xmlns:android="schemas.android.com/apk/res/android"; package="your.package.name"> 

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

但是,如果你定位Android M,在Manifest中声明权限是不够的,你必须在运行时明确询问用户: https://developer.android.com/training/permissions/requesting.html

  

要检查您是否拥有权限,请致电   ContextCompat.checkSelfPermission()方法。例如,这个   片段显示如何检查活动是否具有写入权限   日历:

// Assume thisActivity is the current activity 
int permissionCheck = ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.WRITE_CALENDAR);

因此,在您的情况下,在调用方法deviceUDID之前,请确保您拥有READ_PHONE_STATE权限。

您可以按照指示here的步骤进行操作。