簡體   English   中英

如何確定哪個用戶安裝了android應用程序?

[英]How to determine which user installed the android application?

使用Android 4.2及更高版本的平板電腦,可支持多個用戶。 這意味着每個用戶都可以擁有自己獨立的應用程序集,這些應用程序將與其他用戶分開。 此外,如果用戶A安裝了應用程序,則在用戶B登錄時將無法使用該應用程序。

所以我的問題是,如果在安裝應用程序時有一種方法可以確定使用PackageManager ,我可以知道哪個用戶實際安裝了它嗎?

不幸的是,沒有一種簡單直接的方法可以“識別”哪個用戶安裝了您的應用。 唯一的選擇是將用戶與文檔中所述的唯一ID相關聯:

通過在您的應用首次啟動時創建新的UUID,無論用戶在單個設備上安裝了多少用戶,您都可以獲得用於跟蹤每個用戶的唯一ID。

因此,雖然您可能無法通過某種憑證直接檢索用戶,但您可以使用( 此處的代碼 )模擬您自己的用戶:

public class Installation {
    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();
    }
}

我找到了解決方案。 獲取用戶信息的最佳方法是使用UserManager API。 雖然某些API要求應用程序成為系統應用程序,但我們可以獲取有關當前用戶名,用戶ID等的所有信息。

暫無
暫無

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

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