java - 安卓如何获取DeviceID?

标签 java android

如何在 Android 中获取unically Deviceid? 适用于智能手机和平板电脑。 据我了解,这可能不是唯一的?

这段代码可以工作吗? http://android-developers.blogspot.com/2011/03/identifying-app-installations.html

最佳答案

这是获取设备 ID 的简单方法,也适用于平板电脑

public class DeviceHelper {

private static String sID = null;
private static final String INSTALLATION = "INSTALLATION";

public synchronized static String getDeviceId(final Context context) {
    if (sID == null) {
        File installation = new File(context.getFilesDir(), INSTALLATION);
        try {
            if (!installation.exists()){
                writeInstallationFile(context,installation);
            }
            sID = readInstallationFile(installation);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    return sID;
}

private static String readInstallationFile(File installation) throws IOException {
    RandomAccessFile f = new RandomAccessFile(installation, "r");
    byte[] bytes = new byte[(int) f.length()];
    f.readFully(bytes);
    f.close();
    return new String(bytes);
}

private static void writeInstallationFile(final Context context,File installation) throws IOException {
    FileOutputStream out = new FileOutputStream(installation);
    StringBuffer buf=new StringBuffer();
    buf.append(Settings.Secure.getString(context.getContentResolver(),Settings.Secure.ANDROID_ID));
    buf.append("-");
    buf.append(UUID.randomUUID().toString());
    out.write(buf.toString().getBytes());
    out.close();
}

}

关于java - 安卓如何获取DeviceID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18383053/

相关文章:

java - JPA 保存实体错误

android - 当单行 Snackbar 被滑开时,FAB 没有动画

android - AndroidManifest.xml 中的多个 <application>

java - 转换逻辑以使用 Java 8 Streams

Java比较long值的正确方法

android - 在自定义 View 中设置 textSize 会产生巨大的文本

java - classname.class在Android中指的是什么?

android - 在更新到目标 sdk 29 之前,Javascript 无法在 Android WebView 上运行

java - 如何在 JFreeChart 中绘制填充矩形?

java - 如何在一个 Maven 配置文件和另一个配置文件之间切换?