Code example for SharedPreferences

Methods: getIntgetLonggetString

0
    } 
  } 
 
  public static String getRegistrationId(Context context) {
    final SharedPreferences prefs=getGCMPreferences(context);
    String registrationId=prefs.getString(PROPERTY_REG_ID, "");
    // check if app was updated; if so, it must clear 
    // registration id to 
    // avoid a race condition if GCM sends a message 
    int oldVersion=
        prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
    int newVersion=getAppVersion(context);
    if (oldVersion != Integer.MIN_VALUE && oldVersion != newVersion) {
      Log.v(TAG, "App version changed from " + oldVersion + " to "
          + newVersion + "; resetting registration id");
      clearRegistrationId(context);
      registrationId="";
    } 
    else if (isRegistrationExpired(context)) {
      Log.v(TAG, "Registration expired; resetting registration id");
      clearRegistrationId(context);
      registrationId="";
    } 
    return registrationId;
  } 
 
  public static String clearRegistrationId(Context context) {
    return setRegistrationId(context, "");
  } 
 
  private static String setRegistrationId(Context context, String regId) {
    final SharedPreferences prefs=getGCMPreferences(context);
    String oldRegistrationId=prefs.getString(PROPERTY_REG_ID, "");
    int appVersion=getAppVersion(context);
    long expirationTime=
        System.currentTimeMillis() + REGISTRATION_EXPIRY_TIME_MS;
    Editor editor=prefs.edit();
 
    editor.putString(PROPERTY_REG_ID, regId);
    editor.putInt(PROPERTY_APP_VERSION, appVersion);
    editor.putLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, expirationTime);
    editor.commit();
 
    return oldRegistrationId;
  } 
 
  private static int getAppVersion(Context context) {
    try { 
      PackageInfo packageInfo=
          context.getPackageManager()
                 .getPackageInfo(context.getPackageName(), 0);
      return packageInfo.versionCode;
    } 
    catch (NameNotFoundException e) {
      // should never happen 
      throw new RuntimeException("Coult not get package name: " + e);
    } 
  } 
 
  private static boolean isRegistrationExpired(Context context) {
    final SharedPreferences prefs=getGCMPreferences(context);
    // checks if the information is not stale 
    long expirationTime=
        prefs.getLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, -1);
    return System.currentTimeMillis() > expirationTime;
  } 
 
  private static SharedPreferences getGCMPreferences(Context context) {