下面列出了android.content.SharedPreferences#getLong ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Returns the last time that a notification was shown (in UNIX time)
*
* @param context Used to access SharedPreferences
* @return UNIX time of when the last notification was shown
*/
public static long getLastNotificationTimeInMillis(Context context) {
/* Key for accessing the time at which Sunshine last displayed a notification */
String lastNotificationKey = context.getString(R.string.pref_last_notification);
/* As usual, we use the default SharedPreferences to access the user's preferences */
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
/*
* Here, we retrieve the time in milliseconds when the last notification was shown. If
* SharedPreferences doesn't have a value for lastNotificationKey, we return 0. The reason
* we return 0 is because we compare the value returned from this method to the current
* system time. If the difference between the last notification time and the current time
* is greater than one day, we will show a notification again. When we compare the two
* values, we subtract the last notification time from the current system time. If the
* time of the last notification was 0, the difference will always be greater than the
* number of milliseconds in a day and we will show another notification.
*/
long lastNotificationTime = sp.getLong(lastNotificationKey, 0);
return lastNotificationTime;
}
/**
* 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
*
* @param key
* @param defaultObject
* @return
*/
private static Object getParam(Context context, boolean isUserParams, String key, Object defaultObject) {
String type = defaultObject.getClass().getSimpleName();
SharedPreferences sp = getPref(context, isUserParams ? SP_FILE.USER : SP_FILE.APP);
if ("String".equals(type)) {
return sp.getString(key, (String) defaultObject);
} else if ("Integer".equals(type)) {
return sp.getInt(key, (Integer) defaultObject);
} else if ("Boolean".equals(type)) {
return sp.getBoolean(key, (Boolean) defaultObject);
} else if ("Float".equals(type)) {
return sp.getFloat(key, (Float) defaultObject);
} else if ("Long".equals(type)) {
return sp.getLong(key, (Long) defaultObject);
}
return null;
}
/**
* Retrieve internal id of call handler as saved in databases It should be
* some negative < SipProfile.INVALID_ID number
*
* @param ctxt Application context
* @param packageName name of the call handler package
* @return the id of this call handler in databases
*/
public static Long getAccountIdForCallHandler(Context ctxt, String packageName) {
SharedPreferences prefs = ctxt.getSharedPreferences("handlerCache", Context.MODE_PRIVATE);
long accountId = SipProfile.INVALID_ID;
try {
accountId = prefs.getLong(VIRTUAL_ACC_PREFIX + packageName, SipProfile.INVALID_ID);
} catch (Exception e) {
Log.e(THIS_FILE, "Can't retrieve call handler cache id - reset");
}
if (accountId == SipProfile.INVALID_ID) {
// We never seen this one, add a new entry for account id
int maxAcc = prefs.getInt(VIRTUAL_ACC_MAX_ENTRIES, 0x0);
int currentEntry = maxAcc + 1;
accountId = SipProfile.INVALID_ID - (long) currentEntry;
Editor edt = prefs.edit();
edt.putLong(VIRTUAL_ACC_PREFIX + packageName, accountId);
edt.putInt(VIRTUAL_ACC_MAX_ENTRIES, currentEntry);
edt.commit();
}
return accountId;
}
/**
* 刷新 经典模式-导航 可用数量
*/
private static void updateClassicModeValidNavigationCount(Context context) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
if (sharedPreferences.getLong(CLASSIC_MODE_CURRENT_VALID_NAVIGATION_COUNT, MAX_NAVIGATION_COUNT) < MAX_NAVIGATION_COUNT) {
long intervalTime = System.currentTimeMillis() - sharedPreferences.getLong(CLASSIC_MODE_NAVIGATION_LAST_UPDATE_TIME, 0);
if (intervalTime > NAVIGATION_RECOVER_DURATION) {
long recoverNavigationCount = intervalTime / NAVIGATION_RECOVER_DURATION;
if (recoverNavigationCount > 0) {
recoverNavigationCount += sharedPreferences.getLong(CLASSIC_MODE_CURRENT_VALID_NAVIGATION_COUNT, MAX_NAVIGATION_COUNT);
if (recoverNavigationCount > MAX_NAVIGATION_COUNT) {
recoverNavigationCount = MAX_NAVIGATION_COUNT;
}
saveClassicModeCurrentValidNavigationCount(context, recoverNavigationCount);
}
}
}
}
/**
* Returns the last time that a notification was shown (in UNIX time)
*
* @param context Used to access SharedPreferences
* @return UNIX time of when the last notification was shown
*/
public static long getLastNotificationTimeInMillis(Context context) {
/* Key for accessing the time at which Sunshine last displayed a notification */
String lastNotificationKey = context.getString(R.string.pref_last_notification);
/* As usual, we use the default SharedPreferences to access the user's preferences */
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
/*
* Here, we retrieve the time in milliseconds when the last notification was shown. If
* SharedPreferences doesn't have a value for lastNotificationKey, we return 0. The reason
* we return 0 is because we compare the value returned from this method to the current
* system time. If the difference between the last notification time and the current time
* is greater than one day, we will show a notification again. When we compare the two
* values, we subtract the last notification time from the current system time. If the
* time of the last notification was 0, the difference will always be greater than the
* number of milliseconds in a day and we will show another notification.
*/
long lastNotificationTime = sp.getLong(lastNotificationKey, 0);
return lastNotificationTime;
}
public void saveDataAndClearMemory(List<TrackPoint> trackPoints, Long distance,boolean isLast){
cacheDataToDatabase(trackPoints, isLast);
//更新sp中的距离信息,单位为米
SharedPreferences sp = GlobalApplication.getAppContext().getSharedPreferences(RMConfiguration.FILE_CONFIG, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
if(isLast){
long total = sp.getLong(RMConfiguration.KEY_TOTAL_DISTANCE,0);
total += distance;
editor.putLong(RMConfiguration.KEY_TOTAL_DISTANCE,total);
editor.putLong(RMConfiguration.KEY_TMP_DISTANCE,0);
editor.apply();
}
else{
editor.putLong(RMConfiguration.KEY_TMP_DISTANCE,distance);
editor.apply();
}
}
/**
* 刷新经典模式可用心数量
*/
private static void updateClassicModeValidHeartCount(Context context) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
if (sharedPreferences.getLong(CLASSIC_MODE_CURRENT_VALID_HEART_COUNT, MAX_HEART_COUNT) < MAX_HEART_COUNT) {
long intervalTime = System.currentTimeMillis() - sharedPreferences.getLong(CLASSIC_MODE_HEART_LAST_UPDATE_TIME, 0);
if (intervalTime > HEART_RECOVER_DURATION) {
long recoverHeartCount = intervalTime / HEART_RECOVER_DURATION;
if (recoverHeartCount > 0) {
recoverHeartCount += sharedPreferences.getLong(CLASSIC_MODE_CURRENT_VALID_HEART_COUNT, MAX_HEART_COUNT);
if (recoverHeartCount > MAX_HEART_COUNT) {
recoverHeartCount = MAX_HEART_COUNT;
}
saveClassicModeCurrentValidHeartCount(context, recoverHeartCount);
}
}
}
}
/**
* Returns the last time that a notification was shown (in UNIX time)
*
* @param context Used to access SharedPreferences
* @return UNIX time of when the last notification was shown
*/
public static long getLastNotificationTimeInMillis(Context context) {
/* Key for accessing the time at which Sunshine last displayed a notification */
String lastNotificationKey = context.getString(R.string.pref_last_notification);
/* As usual, we use the default SharedPreferences to access the user's preferences */
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
/*
* Here, we retrieve the time in milliseconds when the last notification was shown. If
* SharedPreferences doesn't have a value for lastNotificationKey, we return 0. The reason
* we return 0 is because we compare the value returned from this method to the current
* system time. If the difference between the last notification time and the current time
* is greater than one day, we will show a notification again. When we compare the two
* values, we subtract the last notification time from the current system time. If the
* time of the last notification was 0, the difference will always be greater than the
* number of milliseconds in a day and we will show another notification.
*/
long lastNotificationTime = sp.getLong(lastNotificationKey, 0);
return lastNotificationTime;
}
/**
* 获取数据
* @param context
* @param key
* @param defValue
* @return
*/
public static Object get(Context context, String key, Object defValue) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
if (defValue instanceof String) {
return sp.getString(key, (String) defValue);
} else if (defValue instanceof Integer) {
return sp.getInt(key, (Integer) defValue);
} else if (defValue instanceof Boolean) {
return sp.getBoolean(key, (Boolean) defValue);
} else if (defValue instanceof Float) {
return sp.getFloat(key, (Float) defValue);
} else if (defValue instanceof Long) {
return sp.getLong(key, (Long) defValue);
}
return null;
}
/**
* SP中读取long
*
* @param key 键
* @return 存在返回对应值,不存在返回默认值-1
*/
public static long getLong(Context context, String key) {
SharedPreferences sp = context.getSharedPreferences(key, Context.MODE_PRIVATE);
long value;
value = sp.getLong(key, -1L);
return value;
}
public long getLong(String keyZone, String key, long defaultValue) {
if (null == this.context) {
LOGGER.w("application context is null");
return defaultValue;
}
SharedPreferences setting = this.context.getSharedPreferences(keyZone, Context.MODE_PRIVATE);
return setting.getLong(key, defaultValue);
}
@Override
protected AccessToken doInBackground(Void... voids) {
final SharedPreferences prefs =
getSharedPreferences(PREFS, Context.MODE_PRIVATE);
String tokenValue = prefs.getString(PREF_ACCESS_TOKEN_VALUE, null);
long expirationTime = prefs.getLong(PREF_ACCESS_TOKEN_EXPIRATION_TIME, -1);
// Check if the current token is still valid for a while
if (tokenValue != null && expirationTime > 0) {
if (expirationTime
> System.currentTimeMillis() + ACCESS_TOKEN_EXPIRATION_TOLERANCE) {
return new AccessToken(tokenValue, new Date(expirationTime));
}
}
// ***** WARNING *****
// In this sample, we load the credential from a JSON file stored in a raw resource
// folder of this client app. You should never do this in your app. Instead, store
// the file in your server and obtain an access token from there.
// *******************
final InputStream stream = getResources().openRawResource(R.raw.credential);
try {
final GoogleCredentials credentials = GoogleCredentials.fromStream(stream)
.createScoped(SCOPE);
final AccessToken token = credentials.refreshAccessToken();
prefs.edit()
.putString(PREF_ACCESS_TOKEN_VALUE, token.getTokenValue())
.putLong(PREF_ACCESS_TOKEN_EXPIRATION_TIME,
token.getExpirationTime().getTime())
.apply();
return token;
} catch (IOException e) {
Log.e(TAG, "Failed to obtain access token.", e);
}
return null;
}
private static Object get(Context context, String key, Object defaultObj) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
if(defaultObj instanceof String) return sp.getString(key, (String)defaultObj);
else if(defaultObj instanceof Integer) return sp.getInt(key, (Integer)defaultObj);
else if(defaultObj instanceof Boolean) return sp.getBoolean(key, (Boolean)defaultObj);
else if(defaultObj instanceof Float) return sp.getFloat(key, (Float)defaultObj);
else if(defaultObj instanceof Long) return sp.getLong(key, (Long)defaultObj);
return defaultObj;
}
/**
* Set firstLaunchDay if neccessary
*/
private void setFirstLaunchDay() {
SharedPreferences preferences = context.getSharedPreferences(Const.SHARED_PREFERENCES, 0);
long firstLaunchDay = preferences.getLong(Const.SHARED_PREFERENCES_DAYS, -1);
if (firstLaunchDay == -1) {
preferences.edit().putLong(Const.SHARED_PREFERENCES_DAYS, System.currentTimeMillis()).apply();
}
}
/**
* 初始化音频的数据
*/
private void initAudio() {
// 获取service存储的数据
recordingItem = new RecordingItem();
SharedPreferences sharePreferences = mActivity.getSharedPreferences("sp_name_audio", MODE_PRIVATE);
final String filePath = sharePreferences.getString("audio_path", "");
long elpased = sharePreferences.getLong("elpased", 0);
recordingItem.setFilePath(filePath);
recordingItem.setLength((int) elpased);
}
public boolean saveLatestLaunchTime() {
long t = System.currentTimeMillis();
String date = StringUtils.timeString(t);
String minutes = StringUtils.timeStringByMinutes(t);
SharedPreferences sp = context.getSharedPreferences(FORCE_ALERT, 0);
if (sp.getLong(PREF_CURRENTTIMEMILLIS, 0) != 0 && t - sp.getLong(PREF_CURRENTTIMEMILLIS, 0) < 300000) {
return false;
}
Editor editor = sp.edit();
editor.putLong(PREF_CURRENTTIMEMILLIS, t);
editor.putString(PREF_LAUNCH_DATE, date);
editor.putString(PREF_LAUNCH_MINUTE, minutes);
editor.commit();
return true;
}
private void checkTimeForAutoTheme(SharedPreferences preferences) {
long toMs;
long fromMs;
boolean auto = preferences.getBoolean(SHP_SETTING.KEY_IS_AUTOMATIC_TIME_DARK_THEME, true);
int offset = TimeZone.getDefault().getRawOffset() + TimeZone.getDefault().getDSTSavings();
long now = System.currentTimeMillis() + offset;
if (auto) {
toMs = 28800000;
fromMs = 68400000;
} else {
toMs = preferences.getLong(SHP_SETTING.KEY_SELECTED_MILISECOND_TO, 28800000);
fromMs = preferences.getLong(SHP_SETTING.KEY_SELECTED_MILISECOND_FROM, 68400000);
}
try {
String string1 = time(fromMs);
Date time1 = new SimpleDateFormat("HH:mm:ss").parse(string1);
String string2 = time(toMs);
Date time2 = new SimpleDateFormat("HH:mm:ss").parse(string2);
String someRandomTime = time(now);
Date currentTime = new SimpleDateFormat("HH:mm:ss").parse(someRandomTime);
if (currentTime.getTime() > time1.getTime() && currentTime.getTime() < time2.getTime()) {
//checkes whether the current time is between 14:49:00 and 20:11:13.
G.isDarkTheme = true;
appBarColor = Theme.default_dark_appBarColor;
notificationColor = Theme.default_dark_notificationColor;
toggleButtonColor = Theme.default_dark_toggleButtonColor;
attachmentColor = Theme.default_dark_attachmentColor;
headerTextColor = Theme.default_dark_headerTextColor;
G.progressColor = Theme.default_dark_progressColor;
} else {
G.isDarkTheme = false;
appBarColor = Theme.default_appBarColor;
notificationColor = Theme.default_notificationColor;
toggleButtonColor = Theme.default_toggleButtonColor;
attachmentColor = Theme.default_attachmentColor;
headerTextColor = Theme.default_headerTextColor;
G.progressColor = Theme.default_progressColor;
}
} catch (ParseException e) {
e.printStackTrace();
}
}
public long getUsageTimeBeforeDonation() {
SharedPreferences preferences = getPreferences();
return preferences.getLong(this.USAGE_TIME_BEFORE_DONATION, 1000 * 60 * 60); // Defaults to 1 hour
}
/**
* get long preferences
*
* @param context context
* @param key The name of the preference to retrieve
* @param defaultValue Value to return if this preference does not exist
* @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with
* this name that is not a long
*/
public static long getLong(Context context, String key, long defaultValue) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
return settings.getLong(key, defaultValue);
}
/**
* Get the user preferred inactivity timeout
*
* @param ctx the application context
* @return the value in milliseconds
*/
public static long getInactivityTimeout(@NonNull final Context ctx) {
final SharedPreferences pref = getPref(ctx);
return pref.getLong(INACTIVITY_TIMEOUT, SelfAwareConditions.DEFAULT_INACTIVITY_TIMEOUT);
}