下面列出了android.content.SharedPreferences#getInt ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
*/
public static Object getSP(Context context, String key, Object defaultObject) {
SharedPreferences sp = context.getSharedPreferences(getSpName(context), Context.MODE_PRIVATE);
if (defaultObject instanceof String) {
return sp.getString(key, (String) defaultObject);
} else if (defaultObject instanceof Integer) {
return sp.getInt(key, (Integer) defaultObject);
} else if (defaultObject instanceof Boolean) {
return sp.getBoolean(key, (Boolean) defaultObject);
} else if (defaultObject instanceof Float) {
return sp.getFloat(key, (Float) defaultObject);
} else if (defaultObject instanceof Long) {
return sp.getLong(key, (Long) defaultObject);
} else {
return null;
}
}
public void checkVersionUpdate(Context ctx, long updateTime)
{
if (!isPlayStoreInstalled(ctx))
{
//check the current install version string against the current version on the alphawallet page
//current version number as string
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(ctx);
int asks = pref.getInt("update_asks", 0);
if (updateTime == 0 || asks == 2) // if user cancels update twice stop asking them until the next release
{
pref.edit().putInt("update_asks", 0).apply();
pref.edit().putLong("install_time", System.currentTimeMillis()).apply();
}
else
{
checkWebsiteAPKFileData(updateTime, ctx);
}
}
}
/**
* 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;
}
GameState(GameStarter gs, Context context){
// This initializes the gameStarter reference
gameStarter = gs;
// Get the current high score
SharedPreferences prefs;
prefs = context.getSharedPreferences("HiScore",
Context.MODE_PRIVATE);
// Initialize the mEditor ready
mEditor = prefs.edit();
// Load high score from a entry in the file
// labeled "hiscore"
// if not available highscore set to zero 0
mHighScore = prefs.getInt("hi_score", 0);
}
public static boolean isNewVersion(Context context) {
PackageInfo packageInfo = getPackageInfo(context);
if (null != packageInfo) {
String versionName = packageInfo.versionName;
int versionCode = packageInfo.versionCode;
SharedPreferences sp = CacheUtils.getPrefs(context);
if (!versionName.equals(sp.getString(CacheUtils.KEY_LAST_VERSION_NAME, null))
|| versionCode != sp.getInt(CacheUtils.KEY_LAST_VERSION_CODE, -1)) {
// new version
NEW_VERSION_NAME = versionName;
NEW_VERSION_CODE = versionCode;
return true;
} else {
return false;
}
} else {
return true;
}
}
public static int readKeypressVibrationDuration(final SharedPreferences prefs,
final Resources res) {
final int milliseconds = prefs.getInt(
PREF_VIBRATION_DURATION_SETTINGS, UNDEFINED_PREFERENCE_VALUE_INT);
return (milliseconds != UNDEFINED_PREFERENCE_VALUE_INT) ? milliseconds
: readDefaultKeypressVibrationDuration(res);
}
private void loadDefaultValue() {
SharedPreferences settings = this.getSharedPreferences("Player_Setting", 0);
m_nVideoQuality = settings.getInt("VideoQuality", 0);
m_nDownloadFile = settings.getInt("DownloadFile", 0);
m_nColorType = settings.getInt("ColorType", 0);
m_nVideoDec = settings.getInt("VideoDec", 1);
setChildValue(POS_VIDEOQUALITY, m_nVideoQuality);
setChildValue(POS_DOWNLOADFILE, m_nDownloadFile);
setChildValue(POS_COLORTYPE, m_nColorType);
setChildValue(POS_VIDEODEC, m_nVideoDec);
}
/**
* 若检查成功,我们会调用TinkerPatchService.runPatchService唤起:patch进程,去尝试完成补丁合成操作。反之,会回调检验失败的接口。
* 若检查失败,会在LoadReporter的onLoadPatchListenerReceiveFail中回调。
* <p>
* because we use the defaultCheckPatchReceived method
* the error code define by myself should after {@code ShareConstants.ERROR_RECOVER_INSERVICE
*
* @param path
* @param newPatch
* @return
*/
@Override
public int patchCheck(String path, String patchMd5) {
File patchFile = new File(path);
TinkerLog.i(TAG, "receive a patch file: %s, file size:%d", path, SharePatchFileUtil.getFileOrDirectorySize(patchFile));
int returnCode = super.patchCheck(path, patchMd5);
if (returnCode == ShareConstants.ERROR_PATCH_OK) {
returnCode = TinkerUtils.checkForPatchRecover(NEW_PATCH_RESTRICTION_SPACE_SIZE_MIN, maxMemory);
}
if (returnCode == ShareConstants.ERROR_PATCH_OK) {
SharedPreferences sp = context.getSharedPreferences(ShareConstants.TINKER_SHARE_PREFERENCE_CONFIG, Context.MODE_MULTI_PROCESS);
//optional, only disable this patch file with md5
int fastCrashCount = sp.getInt(patchMd5, 0);
if (fastCrashCount >= SampleUncaughtExceptionHandler.MAX_CRASH_COUNT) {
returnCode = TinkerUtils.ERROR_PATCH_CRASH_LIMIT;
}
}
// Warning, it is just a sample case, you don't need to copy all of these
// Interception some of the request
if (returnCode == ShareConstants.ERROR_PATCH_OK) {
Properties properties = ShareTinkerInternals.fastGetPatchPackageMeta(patchFile);
if (properties == null) {
returnCode = TinkerUtils.ERROR_PATCH_CONDITION_NOT_SATISFIED;
} else {
String platform = properties.getProperty(TinkerUtils.PLATFORM);
TinkerLog.i(TAG, "get platform:" + platform);
// check patch platform require
if (platform == null || !platform.equals("all")) {
returnCode = TinkerUtils.ERROR_PATCH_CONDITION_NOT_SATISFIED;
}
}
}
SampleTinkerReport.onTryApply(returnCode == ShareConstants.ERROR_PATCH_OK);
return returnCode;
}
public BackupPackagesFilterConfig(SharedPreferences prefs) {
mSortMode = SortMode.values()[prefs.getInt(FILTER_SORT, 0)];
mSortAscending = prefs.getBoolean(SORT_ASCENDING, true);
mSplitApkFilter = SimpleFilterMode.values()[prefs.getInt(FILTER_SPLIT, 1)];
mSystemAppFilter = SimpleFilterMode.values()[prefs.getInt(FILTER_SYSTEM_APP, 0)];
mBackupStatusFilter = BackupStatusFilterMode.values()[prefs.getInt(FILTER_BACKUP_STATUS, 0)];
}
public static int readKeypressVibrationDuration(final SharedPreferences prefs,
final Resources res) {
final int milliseconds = prefs.getInt(
PREF_VIBRATION_DURATION_SETTINGS, UNDEFINED_PREFERENCE_VALUE_INT);
return (milliseconds != UNDEFINED_PREFERENCE_VALUE_INT) ? milliseconds
: readDefaultKeypressVibrationDuration(res);
}
/**
* Function to get default tafseer book id
*
* @return Tafseer book id
*/
public static int getDefaultTafseer() {
SharedPreferences preferences = OpenConfigPreferences();
int type = preferences.getInt(AppConstants.Preferences.DEFAULT_EXPLANATION, -1);
return type;
}
public static int getAutoBackupTime(Context context) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
return sharedPreferences.getInt("auto_backup_time", 600);
}
public static int getInt(String name){
SharedPreferences getspint = App.getContext().getSharedPreferences(name,0);
return getspint.getInt(name,0);
}
public int getGeneralTwitchUserID() {
SharedPreferences preferences = getPreferences();
return preferences.getInt(this.GENERAL_TWITCH_USER_ID, 0);
}
@Override
public void onComplicationUpdate(int complicationId, int type, ComplicationManager manager) {
if (type != ComplicationData.TYPE_SMALL_IMAGE) {
manager.noUpdateRequired(complicationId);
return;
}
ComponentName thisProvider = new ComponentName(this, getClass());
PendingIntent complicationTogglePendingIntent =
ComplicationToggleReceiver.getToggleIntent(this, thisProvider, complicationId);
SharedPreferences preferences =
getSharedPreferences(ComplicationToggleReceiver.PREFERENCES_NAME, 0);
int state =
preferences.getInt(
ComplicationToggleReceiver.getPreferenceKey(thisProvider, complicationId),
0);
ComplicationData data = null;
switch (state % 2) {
case 0:
// An image using IMAGE_STYLE_PHOTO may be cropped to fill the space given to it.
data =
new ComplicationData.Builder(type)
.setSmallImage(Icon.createWithResource(this, R.drawable.aquarium))
.setImageStyle(ComplicationData.IMAGE_STYLE_PHOTO)
.setTapAction(complicationTogglePendingIntent)
.build();
break;
case 1:
// An image using IMAGE_STYLE_ICON must not be cropped, and should fit within the
// space given to it.
data =
new ComplicationData.Builder(type)
.setSmallImage(
Icon.createWithResource(this, R.drawable.ic_launcher))
.setImageStyle(ComplicationData.IMAGE_STYLE_ICON)
.setTapAction(complicationTogglePendingIntent)
.build();
break;
}
manager.updateComplicationData(complicationId, data);
}
/**
* Migrate data from shared preferences to SQLite.
*/
private static void migrateFromSharedPreferences(SQLiteDatabase db) {
synchronized (RequestOld.class) {
Context context = Leanplum.getContext();
SharedPreferences preferences = context.getSharedPreferences(
RequestOld.LEANPLUM, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
int count = preferences.getInt(Constants.Defaults.COUNT_KEY, 0);
if (count == 0) {
return;
}
List<Map<String, Object>> requestData = new ArrayList<>();
for (int i = 0; i < count; i++) {
String itemKey = String.format(Locale.US, Constants.Defaults.ITEM_KEY, i);
Map<String, Object> requestArgs;
try {
requestArgs = JsonConverter.mapFromJson(new JSONObject(
preferences.getString(itemKey, "{}")));
requestData.add(requestArgs);
} catch (JSONException e) {
e.printStackTrace();
}
editor.remove(itemKey);
}
editor.remove(Constants.Defaults.COUNT_KEY);
ContentValues contentValues = new ContentValues();
try {
String uuid = preferences.getString(Constants.Defaults.UUID_KEY, null);
if (uuid == null || count % RequestOld.MAX_EVENTS_PER_API_CALL == 0) {
uuid = UUID.randomUUID().toString();
editor.putString(Constants.Defaults.UUID_KEY, uuid);
}
for (Map<String, Object> event : requestData) {
event.put(RequestOld.UUID_KEY, uuid);
contentValues.put(COLUMN_DATA, JsonConverter.toJson(event));
db.insert(EVENT_TABLE_NAME, null, contentValues);
contentValues.clear();
}
SharedPreferencesUtil.commitChanges(editor);
} catch (Throwable t) {
Log.e("Failed on migration data from shared preferences.", t);
Util.handleException(t);
}
}
}
/**
public void setAvatarBorder(int status, RoundedAvatarDrawable avatar) {
switch (status) {
case Presence.AVAILABLE:
avatar.setBorderColor(getResources().getColor(R.color.holo_green_light));
break;
case Presence.IDLE:
avatar.setBorderColor(getResources().getColor(R.color.holo_green_dark));
break;
case Presence.AWAY:
avatar.setBorderColor(getResources().getColor(R.color.holo_orange_light));
break;
case Presence.DO_NOT_DISTURB:
avatar.setBorderColor(getResources().getColor(R.color.holo_red_dark));
break;
case Presence.OFFLINE:
avatar.setBorderColor(getResources().getColor(R.color.holo_grey_light));
break;
default:
}
}**/
public void applyStyleColors ()
{
//not set color
final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext());
int themeColorHeader = settings.getInt("themeColor",-1);
int themeColorText = settings.getInt("themeColorText",-1);
int themeColorBg = settings.getInt("themeColorBg",-1);
if (mHolder != null) {
if (themeColorText != -1) {
if (mHolder.mTextViewForMessages != null)
mHolder.mTextViewForMessages.setTextColor(themeColorText);
if (mHolder.mTextViewForTimestamp != null)
mHolder.mTextViewForTimestamp.setTextColor(themeColorText);
}
if (themeColorBg != -1)
{
int textBubbleBg = getContrastColor(themeColorText);
if (textBubbleBg == Color.BLACK)
mHolder.mContainer.setBackgroundResource(R.drawable.message_view_rounded_dark);
else
mHolder.mContainer.setBackgroundResource(R.drawable.message_view_rounded_light);
//mHolder.mContainer.setBackgroundResource(android.R.color.transparent);
//mHolder.mContainer.setBackgroundColor(themeColorBg);
}
else
{
mHolder.mContainer.setBackgroundResource(R.drawable.message_view_rounded_light);
}
}
}
/**
* Get the user default action for an unknown command
*
* @param ctx the application context
* @return the action constant
*/
public static int getCommandUnknownAction(@NonNull final Context ctx) {
final SharedPreferences pref = getPref(ctx);
return pref.getInt(COMMAND_UNKNOWN_ACTION, Unknown.UNKNOWN_STATE);
}
/**
* Get the amount of times the user has been informed of this verbose information
*
* @param ctx the application context
* @return the integer number of times
*/
public static int getTranslateCommandVerbose(@NonNull final Context ctx) {
final SharedPreferences pref = getPref(ctx);
return pref.getInt(TRANSLATE_COMMAND_VERBOSE, ZERO);
}
/**
* Get the user preferred Text to Speech volume level
*
* @param ctx the application context
* @return the user preferred volume level
*/
public static int getTTSVolume(@NonNull final Context ctx) {
final SharedPreferences pref = getPref(ctx);
return pref.getInt(TTS_VOLUME, ZERO);
}