| 1 | // Copyright 2013 The Chromium Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | package org.chromium.chrome.browser.identity; |
| 6 | |
| 7 | import android.content.Context; |
| 8 | import android.content.SharedPreferences; |
| 9 | import android.preference.PreferenceManager; |
| 10 | |
| 11 | import com.google.common.annotations.VisibleForTesting; |
| 12 | |
| 13 | import java.util.UUID; |
| 14 | |
| 15 | import javax.annotation.Nullable; |
| 16 | |
| 17 | /** |
| 18 | * Generates unique IDs that are {@link UUID} strings. |
| 19 | */ |
| 20 | public class UuidBasedUniqueIdentificationGenerator implements UniqueIdentificationGenerator { |
| 21 | private final Context mContext; |
| 22 | private final String mPreferenceKey; |
| 23 | |
| 24 | public UuidBasedUniqueIdentificationGenerator(Context context, String preferenceKey) { |
| 25 | mContext = context; |
| 26 | mPreferenceKey = preferenceKey; |
| 27 | } |
| 28 | |
| 29 | @Override |
| 30 | public String getUniqueId(@Nullable String salt) { |
| 31 | SharedPreferences preferences = PreferenceManager |
| 32 | .getDefaultSharedPreferences(mContext); |
| 33 | String storedUniqueId = preferences.getString(mPreferenceKey, null); |
| 34 | if (storedUniqueId != null) { |
| 35 | return storedUniqueId; |
| 36 | } |
| 37 | |
| 38 | // Generate a new unique ID. |
| 39 | String uniqueId = getUUID(); |
| 40 | |
| 41 | // Store the field so we ensure we always return the same unique ID. |
| 42 | SharedPreferences.Editor editor = preferences.edit(); |
| 43 | editor.putString(mPreferenceKey, uniqueId); |
| 44 | editor.apply(); |
| 45 | return uniqueId; |
| 46 | |
| 47 | } |
| 48 | |
| 49 | @VisibleForTesting |
| 50 | String getUUID() { |
| 51 | return UUID.randomUUID().toString(); |
| 52 | } |
| 53 | } |