Java tutorial
//package com.java2s; //License from project: Apache License import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import java.util.UUID; public class Main { private static final String PREF_FILE_KEY = "be.scuad.nmct.be.scuad.PREFERENCE_FILE_KEY"; private static final String PREF_ACTIVE_ACCOUNT = "active_account"; private static final String PREFIX_PREF_GCM_KEY = "gcm_key_"; public static String getGcmKey(final Context context, final String accountName) { SharedPreferences sp = getSharedPreferences(context); String gcmKey = sp.getString(makeAccountSpecificPrefKey(accountName, PREFIX_PREF_GCM_KEY), null); // if there is no current GCM key, generate a new random one if (TextUtils.isEmpty(gcmKey)) { gcmKey = UUID.randomUUID().toString(); setGcmKey(context, accountName, gcmKey); } return gcmKey; } private static SharedPreferences getSharedPreferences(final Context context) { return context.getSharedPreferences(PREF_FILE_KEY, Context.MODE_PRIVATE); } private static String makeAccountSpecificPrefKey(Context ctx, String prefix) { return hasActiveAccount(ctx) ? makeAccountSpecificPrefKey(getActiveAccountName(ctx), prefix) : null; } private static String makeAccountSpecificPrefKey(String accountName, String prefix) { return prefix + accountName; } public static void setGcmKey(final Context context, final String accountName, final String gcmKey) { SharedPreferences sp = getSharedPreferences(context); sp.edit().putString(makeAccountSpecificPrefKey(accountName, PREFIX_PREF_GCM_KEY), gcmKey).apply(); } public static boolean hasActiveAccount(final Context context) { return !TextUtils.isEmpty(getActiveAccountName(context)); } public static String getActiveAccountName(final Context context) { SharedPreferences sp = getSharedPreferences(context); return sp.getString(PREF_ACTIVE_ACCOUNT, null); } }