【发布时间】:2012-02-07 14:15:16
【问题描述】:
我正在尝试实现下面找到的代码,以便在安装应用程序时为用户生成一个随机 ID 号。我只有几个问题。
- 如果我为此创建一个新文件 (Install.java),我如何访问另一个类中的 ID?
-
如何确保在首次安装应用程序时执行这部分程序?现在,程序从我的 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(); } }
【问题讨论】:
-
我敦促您不要写入文件(您不知道所有手机品牌和型号都可以使用哪些设备),而是使用 Preferences 或 SharedPreferences 对象。除此之外,您还可以利用 BackupManager,因此如果用户在另一部手机上安装应用程序,BackupManager 会将所有存储的首选项复制到新手机。
-
@RichardGreen 感谢您的回复。我现在正在尝试使用 SharedPreference 来实现这一点,但我遇到了很多麻烦。你能看看我的另一篇文章,告诉我在哪里以及如何在给定的代码中实现它吗?这是一个链接:stackoverflow.com/questions/9177092/…
标签: java android installation uuid