本文整理了Java中android.content.SharedPreferences
类的一些代码示例,展示了SharedPreferences
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。SharedPreferences
类的具体详情如下:
包路径:android.content.SharedPreferences
类名称:SharedPreferences
[英]Interface for accessing and modifying preference data returned by Context#getSharedPreferences. For any particular set of preferences, there is a single instance of this class that all clients share. Modifications to the preferences must go through an Editor object to ensure the preference values remain in a consistent state and control when they are committed to storage. Objects that are returned from the various get
methods must be treated as immutable by the application.
Note: currently this class does not support use across multiple processes. This will be added later.
For more information about using SharedPreferences, read the Data Storage developer guide.
[中]用于访问和修改上下文#GetSharedReferences返回的首选项数据的接口。对于任何特定的首选项集,该类都有一个所有客户端共享的实例。对首选项的修改必须经过一个编辑器对象,以确保首选项值保持一致的状态,并在提交到存储时进行控制。应用程序必须将从各种get
方法返回的对象视为不可变的。
注意:目前此类不支持跨多个进程使用。这将在以后添加
####开发者指南
有关使用SharedReferences的更多信息,请阅读Data Storage开发者指南。
代码示例来源:origin: Tencent/tinker
/**
* you can set Tinker disable in runtime at some times!
*
* @param context
*/
public static void setTinkerDisableWithSharedPreferences(Context context) {
SharedPreferences sp = context.getSharedPreferences(ShareConstants.TINKER_SHARE_PREFERENCE_CONFIG, Context.MODE_MULTI_PROCESS);
String keyName = ShareConstants.TINKER_ENABLE_CONFIG_PREFIX + ShareConstants.TINKER_VERSION;
sp.edit().putBoolean(keyName, false).commit();
}
代码示例来源:origin: stackoverflow.com
final SharedPreferences prefs = new ObscuredSharedPreferences(
this, this.getSharedPreferences(MY_PREFS_FILE_NAME, Context.MODE_PRIVATE) );
// eg.
prefs.edit().putString("foo","bar").commit();
prefs.getString("foo", null);
代码示例来源:origin: libgdx/libgdx
@Override
public boolean getBoolean (String key) {
return sharedPrefs.getBoolean(key, false);
}
代码示例来源:origin: stackoverflow.com
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
}
代码示例来源:origin: stackoverflow.com
double getDouble(final SharedPreferences prefs, final String key, final double defaultValue) {
if ( !prefs.contains(key))
return defaultValue;
return Double.longBitsToDouble(prefs.getLong(key, 0));
}
代码示例来源:origin: stackoverflow.com
public class MainActivity extends ActionBarActivity {
private Button button;
private SharedPreferences preferences;
private String[] name = {"aa", "bb", "cc"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button1);
preferences=getSharedPreferences("testarray", MODE_PRIVATE);
for(int i=0;i<3;i++)
{
SharedPreferences.Editor editor=preferences.edit();
editor.putString("str"+i, name[i]);
editor.commit();
}
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,Secondact.class));
}
});
}
}
代码示例来源:origin: LawnchairLauncher/Lawnchair
Intent intentAction = new Intent(context, UpdateReceiver.class);
intentAction.putExtra("downloadLink", url);
intentAction.putExtra("filename", url.substring(url.lastIndexOf('/') + 1, url.length()));
.setContentTitle(context.getResources().getString(R.string.update_available_title))
.setContentText(context.getResources().getString(R.string.update_available))
.setSmallIcon(R.drawable.ic_lawnchair)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, builder.build());
prefs.edit()
.putLong(PREFERENCES_LAST_CHECKED, System.currentTimeMillis())
.putString(PREFERENCES_CACHED_UPDATE, update.toString())
.apply();
代码示例来源:origin: ankidroid/Anki-Android
mSource = getIntent().getExtras().getString(EXTRA_SOURCE);
} catch (Exception e) {
mSource = "";
TextView tv = new TextView(this);
tv.setText(getText(R.string.multimedia_editor_trans_poweredglosbe));
linearLayout.addView(tv);
TextView tvFrom = new TextView(this);
tvFrom.setText(getText(R.string.multimedia_editor_trans_from));
linearLayout.addView(tvFrom);
String fromLang = preferences.getString("translatorLastLanguageFrom", "");
String toLang = preferences.getString("translatorLastLanguageTo", "");
mSpinnerFrom.setSelection(getSpinnerIndex(mSpinnerFrom, fromLang));
mSpinnerTo.setSelection(getSpinnerIndex(mSpinnerTo, toLang));
Button btnDone = new Button(this);
btnDone.setText(getText(R.string.multimedia_editor_trans_translate));
btnDone.setOnClickListener(v -> {
preferences.edit().putString("translatorLastLanguageFrom", fromLang1).apply();
preferences.edit().putString("translatorLastLanguageTo", toLang1).apply();
代码示例来源:origin: Iamasoldier6/SoldierWeather
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.switch_city:
Intent intent = new Intent(this, ChooseAreaActivity.class);
intent.putExtra("from_weather_activity", true);
startActivity(intent);
finish();
break;
case R.id.refresh_weather:
weatherDespText.setText("同步中");
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String districtName = preferences.getString("district_name", "");
queryWeather(districtName);
break;
default:
break;
}
}
}
代码示例来源:origin: stackoverflow.com
a = prefs.getString("KEY_FIRST","");
et3.setText(a);
btn.setOnClickListener(new View.OnClickListener()
Intent t = new Intent(this,Kl_Activity.class);
startActivity(t);
代码示例来源:origin: TommyLemon/APIJSON
@Override
public void finish() {
//保存配置
getSharedPreferences(SelectActivity.CONFIG_PATH, Context.MODE_PRIVATE)
.edit()
.remove(KEY_REQUEST)
.putString(KEY_REQUEST, StringUtil.getTrimedString(tvAutoRequest))
.commit();
//需要在SelectActivity实时更新
setResult(RESULT_OK, new Intent().
putExtra(RequestActivity.RESULT_ID, id).
putExtra(RequestActivity.RESULT_URL, url));
super.finish();
}
代码示例来源:origin: ankidroid/Anki-Android
WebView webView;
mType = getIntent().getIntExtra(TYPE_EXTRA, TYPE_ABOUT);
marketButton.setOnClickListener(arg0 -> {
if (mType == TYPE_ABOUT) {
if (CompatHelper.isKindle()) {
Intent intent = new Intent("android.intent.action.VIEW",
Uri.parse("http://www.amazon.com/gp/mas/dl/android?p=com.ichi2.anki"));
startActivityWithoutAnimation(intent);
} else {
Info.this.startActivityWithoutAnimation(new Intent(Intent.ACTION_VIEW, Uri
.parse("market://details?id=com.ichi2.anki")));
switch (mType) {
case TYPE_NEW_VERSION:
AnkiDroidApp.getSharedPrefs(Info.this.getBaseContext()).edit()
.putString("lastVersion", VersionUtils.getPkgVersionName()).apply();
break;
sb.append("</body></html>");
webView.loadDataWithBaseURL("", sb.toString(), "text/html", "utf-8", null);
((Button) findViewById(R.id.market)).setText(res.getString(R.string.info_rate));
Button debugCopy = (findViewById(R.id.debug_info));
debugCopy.setText(res.getString(R.string.feedback_copy_debug));
debugCopy.setVisibility(View.VISIBLE);
debugCopy.setOnClickListener(v -> copyDebugInfo());
代码示例来源:origin: Iamasoldier6/SoldierWeather
/**
* 从SharedPreferences文件中读取存储的天气信息,并显示到界面上
*/
private void showWeather() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
LogUtil.log("WeatherActivity", "cityName = " + prefs.getString("city_name", ""));
LogUtil.log("WeatherActivity", "temperature = " + prefs.getString("temperature", ""));
LogUtil.log("WeatherActivity", "weather = " + prefs.getString("weather", ""));
LogUtil.log("WeatherActivity", "date = " + prefs.getString("date", ""));
cityNameText.setText(prefs.getString("city_name", ""));
weatherDespText.setText(prefs.getString("weather", ""));
temperature.setText(prefs.getString("temperature", ""));
currentDateText.setText(prefs.getString("date", ""));
Intent intent = new Intent(this, AutoUpdateService.class);
startService(intent);
}
代码示例来源:origin: avjinder/Minimal-Todo
app.send(this);
theme = getActivity().getSharedPreferences(MainFragment.THEME_PREFERENCES, MODE_PRIVATE).getString(MainFragment.THEME_SAVED, MainFragment.LIGHTTHEME);
if (theme.equals(MainFragment.LIGHTTHEME)) {
getActivity().setTheme(R.style.CustomStyle_LightTheme);
UUID id = (UUID) i.getSerializableExtra(TodoNotificationService.TODOUUID);
mItem = null;
for (ToDoItem toDoItem : mToDoItems) {
mtoDoTextTextView.setText(mItem.getToDoText());
mSnoozeTextView.setTextColor(getResources().getColor(R.color.secondary_text));
} else {
mSnoozeTextView.setTextColor(Color.WHITE);
mSnoozeTextView.setCompoundDrawablesWithIntrinsicBounds(
R.drawable.ic_snooze_white_24dp, 0, 0, 0
mRemoveToDoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
代码示例来源:origin: ankidroid/Anki-Android
public static void scheduleNotification(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
if (Integer.parseInt(sp.getString("minimumCardsDueForNotification", "1000001")) <= 1000000) {
return;
}
final Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, sp.getInt("dayOffset", 0));
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
final PendingIntent notificationIntent =
PendingIntent.getBroadcast(context, 0, new Intent(context, NotificationService.class), 0);
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY,
notificationIntent
);
}
}
代码示例来源:origin: hussien89aa/AndroidTutorialForBeginners
void LoadData(){
MyTrackers.clear();
PhoneNumber= ShredRef.getString("PhoneNumber","empty");
String MyTrackersList= ShredRef.getString("MyTrackers","empty");
if (!MyTrackersList.equals("empty")){
String[] users=MyTrackersList.split("%");
for (int i=0;i<users.length;i=i+2){
MyTrackers.put(users[i],users[i+1]);
}
}
if (PhoneNumber.equals("empty")){
Intent intent=new Intent(context, Login.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
代码示例来源:origin: Swati4star/Images-to-PDF
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case MODIFY_STORAGE_LOCATION_CODE:
if (data.getExtras() != null) {
String folderLocation = data.getExtras().getString("data") + "/";
Log.i("folderLocation", folderLocation);
mSharedPreferences.edit().putString(STORAGE_LOCATION, folderLocation).apply();
showSnackbar(mActivity, R.string.storage_location_modified);
storageLocation.setText(mSharedPreferences.getString(STORAGE_LOCATION,
getDefaultStorageLocation()));
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
代码示例来源:origin: scwang90/SmartRefreshLayout
public ClassicsHeader setLastUpdateTime(Date time) {
final View thisView = this;
mLastTime = time;
mLastUpdateText.setText(mLastUpdateFormat.format(time));
if (mShared != null && !thisView.isInEditMode()) {
mShared.edit().putLong(KEY_LAST_UPDATE_TIME, time.getTime()).apply();
}
return this;
}
代码示例来源:origin: syncthing/syncthing-android
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FolderPickerActivity.DIRECTORY_REQUEST_CODE && resultCode == RESULT_OK) {
Folder selectedFolder = (Folder) mFoldersSpinner.getSelectedItem();
String folderDirectory = Util.formatPath(selectedFolder.path);
String subDirectory = data.getStringExtra(FolderPickerActivity.EXTRA_RESULT_DIRECTORY);
//Remove the parent directory from the string, so it is only the Sub directory that is displayed to the user.
subDirectory = subDirectory.replace(folderDirectory, "");
mSubDirectoryTextView.setText(subDirectory);
PreferenceManager.getDefaultSharedPreferences(this)
.edit().putString(PREF_FOLDER_SAVED_SUBDIRECTORY + selectedFolder.id, subDirectory)
.apply();
}
}
}
代码示例来源:origin: avjinder/Minimal-Todo
private void closeApp() {
Intent i = new Intent(getContext(), MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// i.putExtra(EXIT, true);
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(MainFragment.SHARED_PREF_DATA_SET_CHANGED, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(EXIT, true);
editor.apply();
startActivity(i);
}
内容来源于网络,如有侵权,请联系作者删除!