簡體   English   中英

在應用程序安裝時設置唯一ID-Android

[英]Setting a Unique ID at Application Install - Android

我正在嘗試實現以下代碼,以便在安裝應用程序時可以為用戶權限生成隨機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();
    }
    ......

據我所知,安裝完成后,您無法立即運行任何任意代碼。

我認為可以得到的最接近的方法是在MainActivity onCreate()方法中進行檢查,以確定是否是第一次運行(檢查此方法的一種好方法可能是獲取對文件的引用並調用file.exists( ),生成的布爾值將告訴您是否需要創建UID文件。

這是蒂姆·布雷(Tim Bray)的博客文章,解釋了您實際上應該做什么。

http://android-developers.blogspot.com/2011/03/identifying-app-installations.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM