List of usage examples for android.content SharedPreferences getLong
long getLong(String key, long defValue);
From source file:org.tigase.messenger.phone.pro.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar);// w w w. j av a 2 s . c o m /* * FloatingActionButton fab = (FloatingActionButton) * findViewById(R.id.fab); fab.setOnClickListener(new * View.OnClickListener() { * * @Override public void onClick(View view) { Snackbar.make(view, * "Replace with your own action", Snackbar.LENGTH_LONG) * .setAction("Action", null).show(); } }); */ final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); this.navigationMenu = navigationView.getMenu(); View headerLayout = navigationView.getHeaderView(0); this.statusSelector = (Spinner) headerLayout.findViewById(R.id.status_selector); final SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); switch (sharedPref.getString("menu", "roster")) { case "roster": switchMainFragment(R.id.nav_roster); break; case "connectionstatus": switchMainFragment(R.id.nav_connectionstatus); break; default: switchMainFragment(R.id.nav_chats); break; } StatusSelectorAdapter statusAdapter = StatusSelectorAdapter.instance(this); statusSelector.setAdapter(statusAdapter); statusSelector.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { doPresenceChange(id); drawer.closeDrawers(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); statusSelector.setSelection(statusAdapter.getPosition(sharedPref.getLong("presence", CPresence.OFFLINE))); final AccountManager am = AccountManager.get(this); Account[] accounts = am.getAccountsByType(Authenticator.ACCOUNT_TYPE); if (accounts == null || accounts.length == 0) { Intent intent = new Intent(this, NewAccountActivity.class); startActivity(intent); } }
From source file:org.croudtrip.fragments.join.JoinDrivingFragment.java
private void updateTrip(final JoinTripRequestUpdateType updateType, final ProgressWheel progressBar) { //show loading indicator if (progressBar != null) { progressBar.setVisibility(View.VISIBLE); }//from w w w .j av a2s . c om final SharedPreferences prefs = getActivity().getSharedPreferences(Constants.SHARED_PREF_FILE_PREFERENCES, Context.MODE_PRIVATE); //send update trip request to server JoinTripRequestUpdate requestUpdate = new JoinTripRequestUpdate(updateType); Subscription subscription = tripsResource .updateJoinRequest(prefs.getLong(Constants.SHARED_PREF_KEY_TRIP_ID, -1), requestUpdate) .compose(new DefaultTransformer<JoinTripRequest>()).subscribe(new Action1<JoinTripRequest>() { @Override public void call(JoinTripRequest joinTripRequest) { Timber.d("update trip successfully called"); adapter.updateRequest(joinTripRequest); //hide loading indicator if (progressBar != null) { progressBar.setVisibility(View.GONE); } if (updateType.equals(JoinTripRequestUpdateType.CANCEL)) { //if a user cancelled everything related to the status can be erased locally // + redirection to the search screen sendUserBackToSearch(); return; } else if (updateType.equals(JoinTripRequestUpdateType.LEAVE_CAR)) { //Check if this was the last part of a supertrip tripsResource.getAllActiveTrips(new Callback<List<SuperTrip>>() { @Override public void success(List<SuperTrip> superTrips, Response response) { if (superTrips.size() == 0) { //no trips active anymore means that the passenger has reached the destination... sendUserBackToSearch(); } else { //..otherwise he must be able to enter the next car //get JoinTripRequest for the remaining SuperTrip tripsResource.getJoinTripRequestsForSuperTrip(superTrips.get(0).getId(), new Callback<List<JoinTripRequest>>() { @Override public void success(List<JoinTripRequest> joinTripRequests, Response response) { //get the next JoinTripRequest JoinTripRequest nextRequest = null; //the next request which was accepted by passenger+driver but the passenger did not enter the //car yet is the next part of the SuperTrip for (JoinTripRequest request : joinTripRequests) { if (request.getStatus() .equals(JoinTripStatus.DRIVER_ACCEPTED)) { nextRequest = request; break; } } //No correct JoinTripRequest is found if (nextRequest == null) { showErrorMessage(progressBar); return; } //remove status "driving" locally final SharedPreferences prefs = getActivity() .getSharedPreferences( Constants.SHARED_PREF_FILE_PREFERENCES, Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean(Constants.SHARED_PREF_KEY_DRIVING, false); editor.putLong(Constants.SHARED_PREF_KEY_TRIP_ID, nextRequest.getId()); //will break editor.apply(); LocalBroadcastManager.getInstance(getActivity()) .registerReceiver(nfcScannedReceiver, new IntentFilter( Constants.EVENT_NFC_TAG_SCANNED)); //show correct ui elements llWaiting.setVisibility(View.VISIBLE); llDriving.setVisibility(View.GONE); switchToNfcIfAvailable(); //change description and functionality of button back to "driver is here" btnReachedDestination.setText(getResources().getString( R.string.join_trip_results_driverArrival)); btnReachedDestination .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateTrip( JoinTripRequestUpdateType.ENTER_CAR, progressBarDest); } }); } @Override public void failure(RetrofitError error) { showErrorMessage(progressBar); } }); } } @Override public void failure(RetrofitError error) { showErrorMessage(progressBar); } }); } else if (updateType.equals(JoinTripRequestUpdateType.ENTER_CAR)) { //the user is now in the car -> switch to driving status //save status "driving" locally SharedPreferences prefs = getActivity().getSharedPreferences( Constants.SHARED_PREF_FILE_PREFERENCES, Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean(Constants.SHARED_PREF_KEY_DRIVING, true); editor.apply(); //hide nfc related ui elements ivNfcIcon.setVisibility(View.GONE); tvNfcExplanation.setVisibility(View.GONE); //change description of button from "enter car" to "leave car" btnReachedDestination .setText(getResources().getString(R.string.join_trip_results_left_Car)); btnReachedDestination.setVisibility(View.VISIBLE); btnReachedDestination.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateTrip(JoinTripRequestUpdateType.LEAVE_CAR, progressBarDest); } }); //passenger can not cancel while he is in the car -> disable button setButtonInactive(btnCancelTrip); //display or hide the correct view groups llWaiting.setVisibility(View.GONE); llDriving.setVisibility(View.VISIBLE); flMap.setVisibility(View.VISIBLE); } } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { CrashPopup.show(getActivity(), throwable); showErrorMessage(progressBar); } }); subscriptions.add(subscription); }
From source file:com.yek.keyboard.anysoftkeyboard.AskPrefsImpl.java
public void onSharedPreferenceChanged(SharedPreferences sp, String key) { Logger.d(TAG, "**** onSharedPreferenceChanged: "); //statistics//from w w w .jav a 2 s .c om mFirstAppVersionInstalled = sp.getInt(mContext.getString(R.string.settings_key_first_app_version_installed), 0); mFirstTimeAppInstalled = sp.getLong(mContext.getString(R.string.settings_key_first_time_app_installed), 0); mFirstTimeCurrentVersionInstalled = sp .getLong(mContext.getString(R.string.settings_key_first_time_current_version_installed), 0); //now real settings mDomainText = sp.getString("default_domain_text", ".com"); Logger.d(TAG, "** mDomainText: " + mDomainText); mShowKeyPreview = sp.getBoolean(mContext.getString(R.string.settings_key_key_press_shows_preview_popup), mContext.getResources().getBoolean(R.bool.settings_default_key_press_shows_preview_popup)); Logger.d(TAG, "** mShowKeyPreview: " + mShowKeyPreview); mKeyPreviewAboveKey = sp .getString(mContext.getString(R.string.settings_key_key_press_preview_popup_position), mContext.getString(R.string.settings_default_key_press_preview_popup_position)) .equals("above_key"); Logger.d(TAG, "** mKeyPreviewAboveKey: " + mKeyPreviewAboveKey); mShowKeyboardNameText = sp.getBoolean(mContext.getString(R.string.settings_key_show_keyboard_name_text_key), mContext.getResources().getBoolean(R.bool.settings_default_show_keyboard_name_text_value)); Logger.d(TAG, "** mShowKeyboardNameText: " + mShowKeyboardNameText); mShowHintTextOnKeys = sp.getBoolean(mContext.getString(R.string.settings_key_show_hint_text_key), mContext.getResources().getBoolean(R.bool.settings_default_show_hint_text_value)); Logger.d(TAG, "** mShowHintTextOnKeys: " + mShowHintTextOnKeys); // preferences to override theme's hint position mUseCustomHintAlign = sp.getBoolean(mContext.getString(R.string.settings_key_use_custom_hint_align_key), mContext.getResources().getBoolean(R.bool.settings_default_use_custom_hint_align_value)); Logger.d(TAG, "** mUseCustomHintAlign: " + mUseCustomHintAlign); mCustomHintAlign = getIntFromString(sp, mContext.getString(R.string.settings_key_custom_hint_align_key), mContext.getString(R.string.settings_default_custom_hint_align_value)); Logger.d(TAG, "** mCustomHintAlign: " + mCustomHintAlign); mCustomHintVAlign = getIntFromString(sp, mContext.getString(R.string.settings_key_custom_hint_valign_key), mContext.getString(R.string.settings_default_custom_hint_valign_value)); Logger.d(TAG, "** mCustomHintVAlign: " + mCustomHintVAlign); mSwitchKeyboardOnSpace = sp.getBoolean(mContext.getString(R.string.settings_key_switch_keyboard_on_space), mContext.getResources().getBoolean(R.bool.settings_default_switch_to_alphabet_on_space)); Logger.d(TAG, "** mSwitchKeyboardOnSpace: " + mSwitchKeyboardOnSpace); mUseFullScreenInputInLandscape = sp.getBoolean( mContext.getString(R.string.settings_key_landscape_fullscreen), mContext.getResources().getBoolean(R.bool.settings_default_landscape_fullscreen)); Logger.d(TAG, "** mUseFullScreenInputInLandscape: " + mUseFullScreenInputInLandscape); mUseFullScreenInputInPortrait = sp.getBoolean(mContext.getString(R.string.settings_key_portrait_fullscreen), mContext.getResources().getBoolean(R.bool.settings_default_portrait_fullscreen)); Logger.d(TAG, "** mUseFullScreenInputInPortrait: " + mUseFullScreenInputInPortrait); // Fix issue 185 mUseKeyRepeat = sp.getBoolean("use_keyrepeat", true); Logger.d(TAG, "** mUseKeyRepeat: " + mUseKeyRepeat); mKeysHeightFactorInPortrait = getFloatFromString(sp, "zoom_factor_keys_in_portrait", mContext.getString(R.string.settings_default_portrait_keyboard_height_factor)); Logger.d(TAG, "** mKeysHeightFactorInPortrait: " + mKeysHeightFactorInPortrait); if (mKeysHeightFactorInPortrait > 2.0f) { mKeysHeightFactorInPortrait = 2.0f; Logger.d(TAG, "** mKeysHeightFactorInPortrait fixed to: " + mKeysHeightFactorInPortrait); } else if (mKeysHeightFactorInPortrait < 0.2f) { mKeysHeightFactorInPortrait = 0.2f; Logger.d(TAG, "** mKeysHeightFactorInPortrait fixed to: " + mKeysHeightFactorInPortrait); } mKeysHeightFactorInLandscape = getFloatFromString(sp, "zoom_factor_keys_in_landscape", mContext.getString(R.string.settings_default_landscape_keyboard_height_factor)); Logger.d(TAG, "** mKeysHeightFactorInLandscape: " + mKeysHeightFactorInLandscape); if (mKeysHeightFactorInLandscape > 2.0f) { mKeysHeightFactorInLandscape = 2.0f; Logger.d(TAG, "** mKeysHeightFactorInLandscape fixed to: " + mKeysHeightFactorInLandscape); } else if (mKeysHeightFactorInPortrait < 0.2f) { mKeysHeightFactorInPortrait = 0.2f; Logger.d(TAG, "** mKeysHeightFactorInPortrait fixed to: " + mKeysHeightFactorInLandscape); } mInsertSpaceAfterCandidatePick = sp.getBoolean("insert_space_after_word_suggestion_selection", true); Logger.d(TAG, "** mInsertSpaceAfterCandidatePick: " + mInsertSpaceAfterCandidatePick); mSwipeUpKeyCode = getIntFromSwipeConfiguration(sp, R.string.settings_key_swipe_up_action, R.string.swipe_action_value_shift); Logger.d(TAG, "** mSwipeUpKeyCode: " + mSwipeUpKeyCode); mSwipeUpFromSpaceBarKeyCode = getIntFromSwipeConfiguration(sp, R.string.settings_key_swipe_up_from_spacebar_action, R.string.swipe_action_value_utility_keyboard); Logger.d(TAG, "** mSwipeUpFromSpaceBarKeyCode: " + mSwipeUpFromSpaceBarKeyCode); mSwipeDownKeyCode = getIntFromSwipeConfiguration(sp, R.string.settings_key_swipe_down_action, R.string.swipe_action_value_hide); Logger.d(TAG, "** mSwipeDownKeyCode: " + mSwipeDownKeyCode); mSwipeLeftKeyCode = getIntFromSwipeConfiguration(sp, R.string.settings_key_swipe_left_action, R.string.swipe_action_value_next_symbols); Logger.d(TAG, "** mSwipeLeftKeyCode: " + mSwipeLeftKeyCode); mSwipeRightKeyCode = getIntFromSwipeConfiguration(sp, R.string.settings_key_swipe_right_action, R.string.swipe_action_value_next_alphabet); Logger.d(TAG, "** mSwipeRightKeyCode: " + mSwipeRightKeyCode); mPinchKeyCode = getIntFromSwipeConfiguration(sp, R.string.settings_key_pinch_gesture_action, R.string.swipe_action_value_merge_layout); Logger.d(TAG, "** mPinchKeyCode: " + mPinchKeyCode); mSeparateKeyCode = getIntFromSwipeConfiguration(sp, R.string.settings_key_separate_gesture_action, R.string.swipe_action_value_split_layout); Logger.d(TAG, "** mSeparateKeyCode: " + mSeparateKeyCode); mSwipeLeftFromSpaceBarKeyCode = getIntFromSwipeConfiguration(sp, R.string.settings_key_swipe_left_space_bar_action, R.string.swipe_action_value_next_symbols); Logger.d(TAG, "** mSwipeLeftFromSpaceBarKeyCode: " + mSwipeLeftFromSpaceBarKeyCode); mSwipeRightFromSpaceBarKeyCode = getIntFromSwipeConfiguration(sp, R.string.settings_key_swipe_right_space_bar_action, R.string.swipe_action_value_next_alphabet); Logger.d(TAG, "** mSwipeRightFromSpaceBarKeyCode: " + mSwipeRightFromSpaceBarKeyCode); mSwipeLeftWithTwoFingersKeyCode = getIntFromSwipeConfiguration(sp, R.string.settings_key_swipe_left_two_fingers_action, R.string.swipe_action_value_compact_layout_to_left); Logger.d(TAG, "** mSwipeLeftWithTwoFingersKeyCode: " + mSwipeLeftWithTwoFingersKeyCode); mSwipeRightWithTwoFingersKeyCode = getIntFromSwipeConfiguration(sp, R.string.settings_key_swipe_right_two_fingers_action, R.string.swipe_action_value_compact_layout_to_right); Logger.d(TAG, "** mSwipeRightWithTwoFingersKeyCode: " + mSwipeRightWithTwoFingersKeyCode); mActionKeyInvisibleWhenRequested = sp.getBoolean("action_key_invisible_on_disable", false); Logger.d(TAG, "** mActionKeyInvisibleWhenRequested: " + mActionKeyInvisibleWhenRequested); /*mRtlWorkaround = sp.getString("rtl_workaround_detection", "auto"); Logger.d(TAG, "** mRtlWorkaround: "+mRtlWorkaround); */ mIsDoubleSpaceChangesToPeroid = sp.getBoolean("double_space_to_period", true); Logger.d(TAG, "** mIsDoubleSpaceChangesToPeroid: " + mIsDoubleSpaceChangesToPeroid); mShouldPopupForLanguageSwitch = sp.getBoolean( mContext.getString(R.string.settings_key_lang_key_shows_popup), mContext.getResources().getBoolean(R.bool.settings_default_lang_key_shows_popup)); Logger.d(TAG, "** mShouldPopupForLanguageSwitch: " + mShouldPopupForLanguageSwitch); mHideSoftKeyboardWhenPhysicalKeyPressed = sp.getBoolean( mContext.getString(R.string.settings_key_hide_soft_when_physical), mContext.getResources().getBoolean(R.bool.settings_default_hide_soft_when_physical)); Logger.d(TAG, "** mHideSoftKeyboardWhenPhysicalKeyPressed: " + mHideSoftKeyboardWhenPhysicalKeyPressed); mSupportPasswordKeyboardMode = sp.getBoolean( mContext.getString(R.string.settings_key_support_password_keyboard_type_state), mContext.getResources() .getBoolean(R.bool.settings_default_bool_support_password_keyboard_type_state)); Logger.d(TAG, "** mSupportPasswordKeyboardMode: " + mSupportPasswordKeyboardMode); mUse16KeysSymbolsKeyboard = sp.getBoolean( mContext.getString(R.string.settings_key_use_16_keys_symbols_keyboards), mContext.getResources().getBoolean(R.bool.settings_default_use_16_keys_symbols_keyboards)); Logger.d(TAG, "** mUse16KeysSymbolsKeyboard: " + mUse16KeysSymbolsKeyboard); mUseBackword = sp.getBoolean(mContext.getString(R.string.settings_key_use_backword), mContext.getResources().getBoolean(R.bool.settings_default_use_backword)); Logger.d(TAG, "** mUseBackword: " + mUseBackword); mCycleOverAllSymbolsKeyboard = sp.getBoolean(mContext.getString(R.string.settings_key_cycle_all_symbols), mContext.getResources().getBoolean(R.bool.settings_default_cycle_all_symbols)); Logger.d(TAG, "** mCycleOverAllSymbolsKeyboard: " + mCycleOverAllSymbolsKeyboard); mUseCameraKeyForBackspaceBackword = sp.getBoolean( mContext.getString(R.string.settings_key_use_camera_key_for_backspace_backword), mContext.getResources().getBoolean(R.bool.settings_default_use_camera_key_for_backspace_backword)); Logger.d(TAG, "** mUseCameraKeyForBackspaceBackword: " + mUseCameraKeyForBackspaceBackword); mUseVolumeKeyForLeftRight = sp.getBoolean( mContext.getString(R.string.settings_key_use_volume_key_for_left_right), mContext.getResources().getBoolean(R.bool.settings_default_use_volume_key_for_left_right)); Logger.d(TAG, "** mUseVolumeKeyForLeftRight: " + mUseVolumeKeyForLeftRight); mUseContactsDictionary = sp.getBoolean(mContext.getString(R.string.settings_key_use_contacts_dictionary), mContext.getResources().getBoolean(R.bool.settings_default_contacts_dictionary)); Logger.d(TAG, "** mUseContactsDictionary: " + mUseContactsDictionary); mAutoDictionaryInsertionThreshold = getIntFromString(sp, mContext.getString(R.string.settings_key_auto_dictionary_threshold), mContext.getString(R.string.settings_default_auto_dictionary_add_threshold)); Logger.d(TAG, "** mAutoDictionaryInsertionThreshold: " + mAutoDictionaryInsertionThreshold); mIsStickyExtensionKeyboard = sp.getBoolean( mContext.getString(R.string.settings_key_is_sticky_extesion_keyboard), mContext.getResources().getBoolean(R.bool.settings_default_is_sticky_extesion_keyboard)); Logger.d(TAG, "** mIsStickyExtensionKeyboard: " + mIsStickyExtensionKeyboard); mSwipeDistanceThreshold = getIntFromString(sp, mContext.getString(R.string.settings_key_swipe_distance_threshold), mContext.getString(R.string.settings_default_swipe_distance_threshold)); Logger.d(TAG, "** mSwipeDistanceThreshold: " + mSwipeDistanceThreshold); mSwipeVelocityThreshold = getIntFromString(sp, mContext.getString(R.string.settings_key_swipe_velocity_threshold), mContext.getString(R.string.settings_default_swipe_velocity_threshold)); Logger.d(TAG, "** mSwipeVelocityThreshold: " + mSwipeVelocityThreshold); mLongPressTimeout = getIntFromString(sp, mContext.getString(R.string.settings_key_long_press_timeout), mContext.getString(R.string.settings_default_long_press_timeout)); Logger.d(TAG, "** mLongPressTimeout: " + mLongPressTimeout); mMultiTapTimeout = getIntFromString(sp, mContext.getString(R.string.settings_key_multitap_timeout), mContext.getString(R.string.settings_default_multitap_timeout)); Logger.d(TAG, "** mMultiTapTimeout: " + mMultiTapTimeout); mWorkaround_alwaysUseDrawText = sp.getBoolean( mContext.getString(R.string.settings_key_workaround_disable_rtl_fix), getAlwaysUseDrawTextDefault()); Logger.d(TAG, "** mWorkaround_alwaysUseDrawText: " + mWorkaround_alwaysUseDrawText); mInitialKeyboardCondenseState = sp.getString(mContext.getString(R.string.settings_key_default_split_state), mContext.getString(R.string.settings_default_default_split_state)); Logger.d(TAG, "** mInitialKeyboardCondenseState: " + mInitialKeyboardCondenseState); mUseChewbacca = sp.getBoolean(mContext.getString(R.string.settings_key_show_chewbacca), mContext.getResources().getBoolean(R.bool.settings_default_show_chewbacca)); Logger.d(TAG, "** mUseChewbacca: " + mUseChewbacca); mSwapPunctuationAndSpace = sp.getBoolean( mContext.getString(R.string.settings_key_bool_should_swap_punctuation_and_space), mContext.getResources().getBoolean(R.bool.settings_default_bool_should_swap_punctuation_and_space)); Logger.d(TAG, "** mSwapPunctuationAndSpace: " + mSwapPunctuationAndSpace); String animationsLevel = sp.getString(mContext.getString(R.string.settings_key_tweak_animations_level), mContext.getString(R.string.settings_default_tweak_animations_level)); if ("none".equals(animationsLevel)) mAnimationsLevel = AnimationsLevel.None; else if ("some".equals(animationsLevel)) mAnimationsLevel = AnimationsLevel.Some; else mAnimationsLevel = AnimationsLevel.Full; Logger.d(TAG, "** mAnimationsLevel: " + mAnimationsLevel); mAlwaysUseFallBackUserDictionary = sp.getBoolean( mContext.getString(R.string.settings_key_always_use_fallback_user_dictionary), mContext.getResources().getBoolean(R.bool.settings_default_always_use_fallback_user_dictionary)); Logger.d(TAG, "** mAlwaysUseFallBackUserDictionary: " + mAlwaysUseFallBackUserDictionary); mAutomaticallySwitchToAppLayout = sp.getBoolean( mContext.getString(R.string.settings_key_persistent_layout_per_package_id), mContext.getResources().getBoolean(R.bool.settings_default_persistent_layout_per_package_id)); Logger.d(TAG, "** mAutomaticallySwitchToAppLayout: " + mAutomaticallySwitchToAppLayout); mAlwaysHideLanguageKey = sp.getBoolean(mContext.getString(R.string.settings_key_always_hide_language_key), mContext.getResources().getBoolean(R.bool.settings_default_always_hide_language_key)); Logger.d(TAG, "** mAlwaysHideLanguageKey: " + mAutomaticallySwitchToAppLayout); //Some preferences cause rebuild of the keyboard, hence changing the listeners list final LinkedList<OnSharedPreferenceChangeListener> disconnectedList = new LinkedList<>( mPreferencesChangedListeners); for (OnSharedPreferenceChangeListener listener : disconnectedList) { //before notifying, we'll ensure that the listener is still interested in the callback if (mPreferencesChangedListeners.contains(listener)) { listener.onSharedPreferenceChanged(sp, key); } } }
From source file:net.sf.diningout.content.SyncAdapter.java
@Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult result) {/*from w ww . j a v a 2 s .c o m*/ Account selected = Accounts.selected(); if (!account.equals(selected)) { if (selected != null) { // never going to sync this account that wasn't selected ContentResolver.setIsSyncable(account, AUTHORITY, 0); } return; } if (extras.containsKey(SYNC_EXTRAS_INITIALIZE)) { return; // will initialise on first normal sync } Context context = getContext(); SharedPreferences prefs = Prefs.get(context, APP); try { if (!prefs.getBoolean(ACCOUNT_INITIALISED, false)) { // first run, log the user in initUser(context, provider); } if (extras.getBoolean(SYNC_EXTRAS_CONTACTS_ONLY)) { refreshContacts(context, provider); uploadContacts(context, provider); return; } if (!prefs.getBoolean(ONBOARDED, false)) { return; // don't sync yet } long now = System.currentTimeMillis(); // full upload and download daily boolean dailySync = now - prefs.getLong(LAST_SYNC, 0L) >= DAY_IN_MILLIS; if (dailySync || extras.containsKey(SYNC_EXTRAS_MANUAL)) { extras.putBoolean(SYNC_EXTRAS_UPLOAD, true); extras.putBoolean(SYNC_EXTRAS_DOWNLOAD, true); refreshContacts(context, provider); } if (extras.containsKey(SYNC_EXTRAS_UPLOAD) || extras.containsKey(SYNC_EXTRAS_DOWNLOAD)) { uploadContacts(context, provider); uploadRestaurants(provider); uploadReviews(provider); uploadReviewDrafts(provider); } if (extras.containsKey(SYNC_EXTRAS_DOWNLOAD)) { download(provider); prefs.edit().putLong(LAST_SYNC, now).apply(); if (dailySync) { refreshRestaurants(context, provider); geofenceRestaurants(context, provider); } Notifications.sync(context); } if (!prefs.contains(CLOUD_ID)) { // get GCM registration ID and user notification key String id = uploadCloudId(context); if (!TextUtils.isEmpty(id)) { prefs.edit().putString(CLOUD_ID, id).apply(); // todo service returns HTTP 401, probably should decouple this from cloud_id // String key = getCloudNotificationKey(context, selected, id); // if (!TextUtils.isEmpty(key)) { // prefs.edit().putString(CLOUD_NOTIFICATION_KEY, key).apply(); // } } } } catch (RemoteException e) { result.databaseError = true; Log.e(TAG, "syncing the ContentProvider", e); exception(e); } }
From source file:opensource.zeocompanion.ZeoCompanionApplication.java
public void dailyCheck() { // configured to allow an auto-backup? SharedPreferences sPrefs = PreferenceManager.getDefaultSharedPreferences(this); boolean autoEmailEnabled = sPrefs.getBoolean("email_auto_enable", false); boolean sendDatabaseEnabled = sPrefs.getBoolean("email_auto_send_database", false); if (!autoEmailEnabled || !sendDatabaseEnabled) { return;//from ww w. ja va2 s. co m } // yes, has the proper internal passed? long newTimestamp = System.currentTimeMillis(); long autoBackupLastTimestamp = sPrefs.getLong("email_auto_send_database_dest_timestamp_last_sent", 0); String autoBackupRepetitionInterval = sPrefs.getString("email_auto_send_database_repetition", "Weekly"); if (autoBackupLastTimestamp > 0) { long interval = 86400000L; if (autoBackupRepetitionInterval.equals("Weekly")) { interval = interval * 7L; } if (autoBackupLastTimestamp + interval > newTimestamp) { return; } } Log.d(_CTAG + ".dailyCheck", "Auto-backup of ZeoCompanion database invoked"); // yes, backup the database BackupReturnResults results = saveCopyOfDB("auto_"); // will not return null // is there a destination email address? String dest = ""; if (sPrefs.contains("email_auto_send_database_dest")) { dest = ObscuredPrefs.decryptString(sPrefs.getString("email_auto_send_database_dest", "")); } if (dest == null) { if (!results.rAnErrorMessage.isEmpty()) { results.rAnErrorMessage = results.rAnErrorMessage + ". "; } results.rAnErrorMessage = results.rAnErrorMessage + "A destination email address is not configured for the database backup; the backup is only stored on-device."; } else if (dest.isEmpty()) { if (!results.rAnErrorMessage.isEmpty()) { results.rAnErrorMessage = results.rAnErrorMessage + ". "; } results.rAnErrorMessage = results.rAnErrorMessage + "A destination email address is not configured for the database backup; the backup is only stored on-device."; } // send a database backup via direct email in a separate thread String subject = "ZeoCompanion database auto backup"; String body = subject + "; see attachment."; if (results.rTheBackupFile == null || !results.rAnErrorMessage.isEmpty()) { mEmailOutbox.postToOutbox(dest, subject, body, results.rTheBackupFile, results.rAnErrorMessage, null); } else { DirectEmailerThread de = new DirectEmailerThread(this); de.setName("DirectEmailerThread via " + _CTAG + ".dailyCheck"); de.configure(subject, body, results.rTheBackupFile, true); de.configureToAddress(dest); de.start(); } // remember the current timestamp of this auto-backup SharedPreferences.Editor editor = sPrefs.edit(); editor.putLong("email_auto_send_database_dest_timestamp_last_sent", newTimestamp); editor.commit(); }
From source file:de.alosdev.android.customerschoice.CustomersChoice.java
private void internalConfigureByNetwork(final Context context, String fileAddress) { new AsyncTask<String, Void, Void>() { @Override/*from w ww. ja v a2 s .c o m*/ protected Void doInBackground(String... args) { String value = args[0]; try { final SharedPreferences preferences = getPreferences(context); final URL url = new URL(value); log.d(TAG, "read from: ", value); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); // set etag header if existing final String fieldEtag = preferences.getString(getPreferencesKey(value, FIELD_ETAG), null); if (null != fieldEtag) { conn.setRequestProperty("If-None-Match", fieldEtag); } // set modified since header if existing final long fieldLastModified = preferences .getLong(getPreferencesKey(value, FIELD_LAST_MODIFIED), 0); if (fieldLastModified > 0) { conn.setIfModifiedSince(fieldLastModified); } conn.connect(); final int response = conn.getResponseCode(); if (HttpStatus.SC_OK == response) { log.d(TAG, "found file"); readFromInputStream(conn.getInputStream()); // writing caching information into preferences final Editor editor = preferences.edit(); editor.putString(getPreferencesKey(value, FIELD_ETAG), conn.getHeaderField("ETag")); editor.putLong(getPreferencesKey(value, FIELD_LAST_MODIFIED), conn.getHeaderFieldDate("Last-Modified", 0)); editor.commit(); } else if (HttpStatus.SC_NOT_MODIFIED == response) { log.i(TAG, "no updates, file not modified: ", value); } else { log.e(TAG, "cannot read from: ", value, " and get following response code:", response); } } catch (MalformedURLException e) { log.e(TAG, e, "the given URL is malformed: ", value); } catch (IOException e) { log.e(TAG, e, "Error during reading the file: ", value); } return null; } }.execute(fileAddress); }
From source file:com.juick.android.ThreadActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { JuickAdvancedApplication.maybeEnableAcceleration(this); JuickAdvancedApplication.setupTheme(this); //requestWindowFeature(Window.FEATURE_NO_TITLE); //getSherlock().requestFeature(Window.FEATURE_NO_TITLE); final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); super.onCreate(savedInstanceState); handler = new Handler(); Intent i = getIntent();/*from ww w . jav a2 s . co m*/ mid = (MessageID) i.getSerializableExtra("mid"); if (mid == null) { finish(); } messagesSource = (MessagesSource) i.getSerializableExtra("messagesSource"); if (sp.getBoolean("fullScreenThread", false)) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); } setContentView(R.layout.thread); /* findViewById(R.id.gotoMain).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(ThreadActivity.this, MainActivity.class)); } }); */ final View buttons = findViewById(R.id.buttons); bSend = (ImageButton) findViewById(R.id.buttonSend); bSend.setOnClickListener(this); bAttach = (ImageButton) findViewById(R.id.buttonAttachment); bAttach.setOnClickListener(this); etMessage = (EditText) findViewById(R.id.editMessage); if (sp.getBoolean("helvNueFonts", false)) { etMessage.setTypeface(JuickAdvancedApplication.helvNue); /* TextView oldTitle = (TextView)findViewById(R.id.old_title); oldTitle.setTypeface(JuickAdvancedApplication.helvNue); */ } Button cancel = (Button) findViewById(R.id.buttonCancel); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { doCancel(); } }); tvReplyTo = (TextView) findViewById(R.id.textReplyTo); replyToContainer = (RelativeLayout) findViewById(R.id.replyToContainer); setHeight(replyToContainer, 0); showThread = (Button) findViewById(R.id.showThread); draftsButton = (Button) findViewById(R.id.drafts); etMessage.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { etMessage.setHint(""); setHeight(buttons, ActionBar.LayoutParams.WRAP_CONTENT); InputMethodManager inputMgr = (InputMethodManager) getSystemService( Context.INPUT_METHOD_SERVICE); inputMgr.toggleSoftInput(0, 0); } else { etMessage.setHint(R.string.ClickToReply); setHeight(buttons, 0); } //To change body of implemented methods use File | Settings | File Templates. } }); draftsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { class Item { String label; long ts; int index; Item(String label, long ts, int index) { this.label = label; this.ts = ts; this.index = index; } } final ArrayList<Item> items = new ArrayList<Item>(); final SharedPreferences drafts = getSharedPreferences("drafts", MODE_PRIVATE); for (int q = 0; q < 1000; q++) { String msg = drafts.getString("message" + q, null); if (msg != null) { if (msg.length() > 50) msg = msg.substring(0, 50); items.add(new Item(msg, drafts.getLong("timestamp" + q, 0), q)); } } Collections.sort(items, new Comparator<Item>() { @Override public int compare(Item item, Item item2) { final long l = item2.ts - item.ts; return l == 0 ? 0 : l > 0 ? 1 : -1; } }); CharSequence[] arr = new CharSequence[items.size()]; for (int i1 = 0; i1 < items.size(); i1++) { Item item = items.get(i1); arr[i1] = item.label; } new AlertDialog.Builder(ThreadActivity.this).setItems(arr, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, final int which) { final Runnable doPull = new Runnable() { @Override public void run() { pullDraft(null, drafts, items.get(which).index); updateDraftsButton(); } }; if (pulledDraft != null && pulledDraft.trim().equals(etMessage.getText().toString().trim())) { // no need to ask, user just looks at the drafts saveDraft(pulledDraftRid, pulledDraftMid, pulledDraftTs, pulledDraft); doPull.run(); } else { if (etMessage.getText().toString().length() > 0) { new AlertDialog.Builder(ThreadActivity.this) .setTitle(getString(R.string.ReplacingText)) .setMessage(getString(R.string.YourTextWillBeReplaced)) .setNegativeButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { doPull.run(); } }) .setNeutralButton( getString(pulledDraft != null ? R.string.SaveChangedDraft : R.string.SaveDraft), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (pulledDraft != null) { saveDraft(pulledDraftRid, pulledDraftMid, System.currentTimeMillis(), etMessage.getText().toString()); } else { saveDraft(rid, mid.toString(), System.currentTimeMillis(), etMessage.getText().toString()); } doPull.run(); } }) .setPositiveButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .show(); } else { doPull.run(); } } } }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }).show(); } }); enableDrafts = (sp.getBoolean("enableDrafts", false)); if (sp.getBoolean("capitalizeReplies", false)) { etMessage.setInputType(etMessage.getInputType() | EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES); } FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); tf = new ThreadFragment(); tf.init(getLastCustomNonConfigurationInstance(), this); Bundle args = new Bundle(); args.putSerializable("mid", mid); args.putSerializable("messagesSource", messagesSource); args.putSerializable("prefetched", i.getSerializableExtra("prefetched")); args.putSerializable("originalMessage", i.getSerializableExtra("originalMessage")); args.putBoolean("scrollToBottom", i.getBooleanExtra("scrollToBottom", false)); tf.setArguments(args); ft.add(R.id.threadfragment, tf); ft.commit(); MainActivity.restyleChildrenOrWidget(getWindow().getDecorView()); detector = new GestureDetector(this, new GestureDetector.OnGestureListener() { @Override public boolean onDown(MotionEvent e) { return false; } @Override public void onShowPress(MotionEvent e) { } @Override public boolean onSingleTapUp(MotionEvent e) { return false; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return false; } @Override public void onLongPress(MotionEvent e) { } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (velocityX > 0 && Math.abs(velocityX) > 4 * Math.abs(velocityY) && Math.abs(velocityX) > 400) { if (etMessage.getText().toString().trim().length() == 0) { System.out.println("velocityX=" + velocityX + " velocityY" + velocityY); if (sp.getBoolean("swipeToClose", true)) { onBackPressed(); } } } return false; } }); com.actionbarsherlock.app.ActionBar actionBar = getSherlock().getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setHomeButtonEnabled(true); actionBar.setLogo(R.drawable.back_button); }
From source file:de.aw.awlib.preferences.AWPreferencesAllgemein.java
@CallSuper @Override//from ww w .j a v a2s. c om public void onCreatePreferences(Bundle bundle, String s) { mApplication = ((AWApplication) getActivity().getApplicationContext()); addPreferencesFromResource(R.xml.awlib_preferences_allgemein); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); for (int pkKey : mPrefs) { String key = getString(pkKey); Preference preference = findPreference(key); if (pkKey == R.string.pkCompileInfo) { java.util.Date date = new Date(BuildConfig.BuildTime); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG); StringBuilder buildInfo = new StringBuilder("Compilezeit: ").append(df.format(date)); preference.setSummary(buildInfo); } else if (pkKey == R.string.pkVersionInfo) { StringBuilder versionInfo = new StringBuilder("Datenbankversion : ") .append(mApplication.theDatenbankVersion()).append(", Version: ") .append(BuildConfig.VERSION_NAME); preference.setSummary(versionInfo); } else if (pkKey == R.string.pkServerUID || pkKey == R.string.pkServerURL) { String value = prefs.getString(key, null); preference.setSummary(value); } else if (pkKey == R.string.pkSavePeriodic) { long value = prefs.getLong(DODATABASESAVE, Long.MAX_VALUE); setRegelmSicherungSummary(preference, prefs, value); } preference.setOnPreferenceClickListener(this); } }
From source file:org.tomahawk.tomahawk_android.activities.TomahawkMainActivity.java
public void showPlaybackPanel(boolean forced) { if (forced || !mSlidingUpPanelLayout.isPanelHidden()) { AnimationUtils.fade(mPlaybackPanel, AnimationUtils.DURATION_CONTEXTMENU, true); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); if (!preferences.getBoolean(COACHMARK_SEEK_DISABLED, false) && preferences.getLong(COACHMARK_SEEK_TIMESTAMP, 0) + 259200000 < System.currentTimeMillis()) { final View coachMark = ViewUtils.ensureInflation(mPlaybackPanel, R.id.playbackpanel_seek_coachmark_stub, R.id.playbackpanel_seek_coachmark); coachMark.findViewById(R.id.close_button).setOnClickListener(new View.OnClickListener() { @Override//from w w w. j a v a 2 s . co m public void onClick(View v) { coachMark.setVisibility(View.GONE); } }); coachMark.setVisibility(View.VISIBLE); preferences.edit().putLong(COACHMARK_SEEK_TIMESTAMP, System.currentTimeMillis()).apply(); } } }
From source file:org.alfresco.mobile.android.application.fragments.node.details.NodeDetailsFragment.java
public Date getDownloadDateTime() { Date d = null;/* w ww .j a v a 2s . c o m*/ SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity()); long activationTime = sharedPref.getLong("Dltime", -1); if (activationTime != -1) { d = new Date(); d.setTime(activationTime); } return d; }