下面列出了android.content.SharedPreferences#getString ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void checkUpgrade(SharedPreferences prefs) {
String lastVersion = prefs.getString(Constants.PREF_APP_VERSION, "");
if (!"".equals(lastVersion) && !BuildConfig.VERSION_NAME.equals(lastVersion)) {
SharedPreferences.Editor editor1 = prefs.edit();
editor1.putString(Constants.PREF_APP_VERSION, BuildConfig.VERSION_NAME);
editor1.apply();
TextView statusTView = findViewById(R.id.start_status);
statusTView.setText(getString(R.string.updatedText));
final String relText = ResourcesUtil.fetchReleaseNotes(this, lastVersion);
TextView textView = findViewById(R.id.start_text);
textView.setText(relText);
updateUi(View.VISIBLE, View.GONE, View.VISIBLE, (view) -> {
mAction = Action.SHOW_INTRO;
onStart();
}, null);
} else {
mAction = Action.SHOW_INTRO;
}
}
private void setOptions() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
swSign.setChecked(prefs.getBoolean("sign_default", false));
swEncrypt.setChecked(prefs.getBoolean("encrypt_default", false));
swSign.setEnabled(!swEncrypt.isChecked());
swAutoDecrypt.setChecked(prefs.getBoolean("auto_decrypt", false));
String provider = prefs.getString("openpgp_provider", "org.sufficientlysecure.keychain");
spOpenPgp.setTag(provider);
for (int pos = 0; pos < openPgpProvider.size(); pos++)
if (provider.equals(openPgpProvider.get(pos))) {
spOpenPgp.setSelection(pos);
break;
}
testOpenPgp(provider);
swAutocrypt.setChecked(prefs.getBoolean("autocrypt", true));
swAutocryptMutual.setChecked(prefs.getBoolean("autocrypt_mutual", true));
swAutocryptMutual.setEnabled(swAutocrypt.isChecked());
swCheckCertificate.setChecked(prefs.getBoolean("check_certificate", true));
}
private void upgradeAutocorrectionSettings(final SharedPreferences prefs, final Resources res) {
final String thresholdSetting =
prefs.getString(PREF_AUTO_CORRECTION_THRESHOLD_OBSOLETE, null);
if (thresholdSetting != null) {
SharedPreferences.Editor editor = prefs.edit();
editor.remove(PREF_AUTO_CORRECTION_THRESHOLD_OBSOLETE);
final String autoCorrectionOff =
res.getString(R.string.auto_correction_threshold_mode_index_off);
if (thresholdSetting.equals(autoCorrectionOff)) {
editor.putBoolean(PREF_AUTO_CORRECTION, false);
} else {
editor.putBoolean(PREF_AUTO_CORRECTION, true);
}
editor.commit();
}
}
@Override
public boolean enableBlocker() {
//contentBlocker56.setUrlBlockLimit(15_000);
if (contentBlocker56.enableBlocker()) {
SharedPreferences sharedPreferences = App.get().getApplicationContext().getSharedPreferences("dnsAddresses", Context.MODE_PRIVATE);
if (sharedPreferences.contains("dns1") && sharedPreferences.contains("dns2")) {
String dns1 = sharedPreferences.getString("dns1", null);
String dns2 = sharedPreferences.getString("dns2", null);
if (dns1 != null && dns2 != null
&& Patterns.IP_ADDRESS.matcher(dns1).matches()
&& Patterns.IP_ADDRESS.matcher(dns2).matches()) {
this.setDns(dns1, dns2);
}
Log.d(TAG, "Previous dns addresses has been applied. " + dns1 + " " + dns2);
}
return true;
}
return false;
}
public static Object get(Context context, String spName, String key, Object defaultObject) {
SharedPreferences sp = context.getSharedPreferences(spName,
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);
}
return null;
}
public static List<String> getTabsOrder(SharedPreferences preferences) {
String order = preferences.getString(FgConst.PREF_TAB_ORDER, "");
String items[] = order.split(";");
List<String> tabs = new ArrayList<>();
try {
for (int i = 0; i < 3; i++) {
if ((items[i].equals(FgConst.FRAGMENT_SUMMARY) | items[i].equals(FgConst.FRAGMENT_ACCOUNTS)
| items[i].equals(FgConst.FRAGMENT_TRANSACTIONS)) & tabs.indexOf(items[i]) < 0) {
tabs.add(items[i]);
} else {
throw new Exception("Parse tabs order preference exception");
}
}
} catch (Exception e) {
tabs.clear();
tabs.add(FgConst.FRAGMENT_SUMMARY);
tabs.add(FgConst.FRAGMENT_ACCOUNTS);
tabs.add(FgConst.FRAGMENT_TRANSACTIONS);
}
return tabs;
}
/**
* 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
*
* @param context
* @param key
* @param defaultObject
* @return
*/
public static Object get(Context context, String key, Object defaultObject)
{
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,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);
}
return null;
}
/**
* 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
*
* @param context
* @param key
* @param defaultObject
* @return
*/
public static Object get(Context context, String key, Object defaultObject) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, 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);
}
return null;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content_view);
setTitle(getIntent().getStringExtra("Title"));
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
course_id = getIntent().getStringExtra("CourseId");
content_id = getIntent().getStringExtra("content_id");
mRecyclerView = findViewById(R.id.recycler_content_view_list);
mSwipeContainer = findViewById(R.id.content_view_swipe_container);
content_view_linear_layout = findViewById(R.id.content_view_linear_layout);
content_view_title = findViewById(R.id.content_view_title);
content_view_time = findViewById(R.id.content_view_time);
content_view_content_detail = findViewById(R.id.content_view_content_detail);
adapter = new ContentViewAdapter(new ArrayList<AttachedFileItem>(), this);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(adapter);
mSwipeContainer.setOnRefreshListener(this);
mSwipeContainer.setColorSchemeColors(getResources().getColor(R.color.colorPrimary), getResources().getColor(R.color.colorAccent));
showLoading(true);
mLoadingTask = new AttachedFilesListLoadingTask();
mLoadingTask.execute((Void) null);
Slidr.attach(this);
SharedPreferences sharedPreferences = getSharedPreferences("login_info", Context.MODE_PRIVATE);
folder = sharedPreferences.getString("path_preference", null);
}
@Override
public void onSecurePreferenceChanged(@NonNull SharedPreferences sharedPreferences, @NonNull DerivedKeyComparison comparison) {
if (comparison.isDerivedKeyEqualTo(expectedKey)) {
newValue = sharedPreferences.getString(expectedKey, null);
numHits++;
}
}
private static byte[] getChallengeIndex(final Context context) {
final SharedPreferences global = PreferenceManager.getDefaultSharedPreferences(context);
final String challengeIndexSerialized = global.getString(KEY_CHALLENGE_INDEX, null);
if (challengeIndexSerialized != null) {
return BaseEncoding.base64().decode(challengeIndexSerialized);
} else {
final byte[] challengeIndex = getChallenge();
global.edit()
.putString(KEY_CHALLENGE_INDEX, BaseEncoding.base64().encode(challengeIndex))
.apply();
return challengeIndex;
}
}
private Locale getLanguageFromSharedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String defaultLanguage = getString(R.string.default_locale);
String language = sharedPreferences.getString(getString(R.string.language_key), defaultLanguage);
if (language.equals(defaultLanguage)) {
return localeUtils.inferDeviceLocale(this);
} else {
return new Locale(language);
}
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
userName = sp.getString(SettingsUtil.USERNAME, "");
password = sp.getString(SettingsUtil.PASSWORD, "");
}
/**
* 获取List<Object>
*
* @param context
* @param key
* @return listBean
*/
public <T> List<T> getListBean(Context context, String key) {
SharedPreferences sp = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
List<T> dataList = new ArrayList<T>();
String strJson = sp.getString(key, null);
if (null == strJson) {
return dataList;
}
Gson gson = new Gson();
dataList = gson.fromJson(strJson, new TypeToken<List<T>>() {
}.getType());
return dataList;
}
/**
* Returns a demo user ID for the current app instance.
*/
static synchronized String getUserId(Context context) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
String userId = sharedPreferences.getString(USER_ID_KEY, null);
if (userId == null) {
userId = UUID.randomUUID().toString();
sharedPreferences.edit().putString(USER_ID_KEY, userId).apply();
}
return userId;
}
static String getOpenKeychainPackage(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getString("openpgp_provider", "org.sufficientlysecure.keychain");
}
private String getUsernameFromPreferences() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(fragActivity);
return preferences.getString(FTPService.KEY_PREFERENCE_USERNAME, FTPService.DEFAULT_USERNAME);
}
protected void startRingtoneAndVibration(int chatID){
SharedPreferences prefs = MessagesController.getNotificationsSettings(currentAccount);
AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
boolean needRing=am.getRingerMode()!=AudioManager.RINGER_MODE_SILENT;
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP){
try{
int mode=Settings.Global.getInt(getContentResolver(), "zen_mode");
if(needRing)
needRing=mode==0;
}catch(Exception ignore){}
}
if(needRing){
if(!USE_CONNECTION_SERVICE){
am.requestAudioFocus(this, AudioManager.STREAM_RING, AudioManager.AUDIOFOCUS_GAIN);
}
ringtonePlayer=new MediaPlayer();
ringtonePlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
@Override
public void onPrepared(MediaPlayer mediaPlayer){
ringtonePlayer.start();
}
});
ringtonePlayer.setLooping(true);
ringtonePlayer.setAudioStreamType(AudioManager.STREAM_RING);
try{
String notificationUri;
if(prefs.getBoolean("custom_"+chatID, false))
notificationUri=prefs.getString("ringtone_path_"+chatID, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE).toString());
else
notificationUri=prefs.getString("CallsRingtonePath", RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE).toString());
ringtonePlayer.setDataSource(this, Uri.parse(notificationUri));
ringtonePlayer.prepareAsync();
}catch(Exception e){
FileLog.e(e);
if(ringtonePlayer!=null){
ringtonePlayer.release();
ringtonePlayer=null;
}
}
int vibrate;
if(prefs.getBoolean("custom_"+chatID, false))
vibrate=prefs.getInt("calls_vibrate_"+chatID, 0);
else
vibrate=prefs.getInt("vibrate_calls", 0);
if((vibrate!=2 && vibrate!=4 && (am.getRingerMode()==AudioManager.RINGER_MODE_VIBRATE || am.getRingerMode()==AudioManager.RINGER_MODE_NORMAL)) ||
(vibrate==4 && am.getRingerMode()==AudioManager.RINGER_MODE_VIBRATE)){
vibrator=(Vibrator) getSystemService(VIBRATOR_SERVICE);
long duration=700;
if(vibrate==1)
duration/=2;
else if(vibrate==3)
duration*=2;
vibrator.vibrate(new long[]{0, duration, 500}, 0);
}
}
}
public String getGeneralTwitchDisplayName() {
SharedPreferences preferences = getPreferences();
return preferences.getString(this.GENERAL_TWITCH_DISPLAY_NAME_KEY, "PocketPlaysDummy");
}
private byte[] decryptIdentityKeyQuickPass(String password) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
String quickPassStringData = sharedPreferences.getString("quickpass", null);
if(quickPassStringData == null) return null;
byte[] quickPassData = EncryptionUtils.hex2Byte(quickPassStringData);
int quickPassIterationCount = getIntFromFourBytes(quickPassData, 0);
byte[] quickPassRandomSalt = Arrays.copyOfRange(quickPassData, 4, 20);
byte[] quickPassInitializationVector = Arrays.copyOfRange(quickPassData, 20, 32);
byte[] quickPassKeyEncrypted = Arrays.copyOfRange(quickPassData, 32, 64);
byte[] quickPassVerificationTag = Arrays.copyOfRange(quickPassData, 64, 80);
this.progressionUpdater.setState(R.string.progress_state_descrypting_identity);
this.progressionUpdater.setMax(quickPassIterationCount);
password = password.substring(0, this.getHintLength());
byte[] quickPassKey = null;
try {
byte[] key = EncryptionUtils.enSCryptIterations(password, quickPassRandomSalt, logNFactor, 32, quickPassIterationCount, this.progressionUpdater);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Key keySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES_256/GCM/NoPadding");
GCMParameterSpec params = new GCMParameterSpec(128, quickPassInitializationVector);
cipher.init(Cipher.DECRYPT_MODE, keySpec, params);
cipher.update(quickPassKeyEncrypted);
try {
quickPassKey = cipher.doFinal(quickPassVerificationTag);
} catch (AEADBadTagException badTag) {
return quickPassKey;
}
} else {
byte[] emptyPlainText = new byte[0];
quickPassKey = new byte[32];
Grc_aesgcm.gcm_setkey(key, key.length);
int res = Grc_aesgcm.gcm_auth_decrypt(
quickPassInitializationVector, quickPassInitializationVector.length,
emptyPlainText, emptyPlainText.length,
quickPassKeyEncrypted, quickPassKey, quickPassKeyEncrypted.length,
quickPassVerificationTag, quickPassVerificationTag.length
);
Grc_aesgcm.gcm_zero_ctx();
if (res == 0x55555555) return quickPassKey;
}
} catch (Exception e) {
Log.e(SQRLStorage.TAG, e.getMessage(), e);
return quickPassKey;
}
return quickPassKey;
}