gpt4 book ai didi

java - 在应用程序安装时设置唯一 ID - Android

转载 作者:行者123 更新时间:2023-11-29 03:50:09 25 4
gpt4 key购买 nike

我正在尝试实现下面的代码,以便在安装应用程序时立即为用户生成一个随机 ID 号。我只有几个问题。

  1. 如果我为此创建一个新文件 (Install.java),我如何访问另一个类中的 ID?
  2. 如何确保在首次安装应用程序时执行这部分程序?现在,程序从我的 Main.java 类开始(我是 Java 的新手)。它会在安装应用程序时运行吗?

    public class Install {

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

    public synchronized static String id(Context context) {
    if (sID == null) {
    File installation = new File(context.getFilesDir(), INSTALLATION);
    try {
    if (!installation.exists())
    writeInstallationFile(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(File installation) throws IOException {
    FileOutputStream out = new FileOutputStream(installation);
    String id = UUID.randomUUID().toString();
    out.write(id.getBytes());
    out.close();
    }
    }

最佳答案

这是我使用的一些代码 - 您可以随意调整...

 public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Log.d(Tag, "Yay onCreate!"); // sorry sometimes I'm a bit verbose with my logs...
createVerifierStrings();
.....


private void createVerifierStrings() {
SharedPreferences prefs = this.getSharedPreferences("Someprefstringreference", 0);
String not_set = "NOTSET";
String android_key;
android_key = prefs.getString("id", not_set);

if (android_key.equals(not_set)) {
Log.d(Tag, "Creating keys for 1st time");
android_key = generateRandomEnoughStuff();
prefs.edit().putString("id", android_key).commit();
}
......

关于java - 在应用程序安装时设置唯一 ID - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9177796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com