Example usage for android.content SharedPreferences getLong

List of usage examples for android.content SharedPreferences getLong

Introduction

In this page you can find the example usage for android.content SharedPreferences getLong.

Prototype

long getLong(String key, long defValue);

Source Link

Document

Retrieve a long value from the preferences.

Usage

From source file:com.cbtec.eliademy.FacebookConnect.java

/**
 * Cordova interface to initialize the appId
 *
 * @param args/*from ww  w  .  j a  va2 s .co  m*/
 * @param callbackId
 * @return PluginResult
 * @throws JSONException
 */
public PluginResult initWithAppId(final JSONArray args, final CallbackContext callbackId) throws JSONException {
    Log.d(CLASS, "initWithAppId()");
    JSONObject params = args.getJSONObject(0);
    PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
    JSONObject result = new JSONObject();

    this.appId = params.getString("appId");
    Facebook facebook = this.getFacebook();
    result.put("appId", this.appId);

    // Check for any stored session update Facebook session information
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(this.cordova.getActivity().getApplicationContext());
    String accessToken = prefs.getString("access_token", null);
    Long accessExpires = prefs.getLong("access_expires", 0);
    if (accessToken != null)
        facebook.setAccessToken(accessToken);
    if (accessExpires != 0)
        facebook.setAccessExpires(accessExpires);

    result.put("accessToken", accessToken);
    result.put("expirationDate", accessExpires);

    pluginResult = new PluginResult(PluginResult.Status.OK, result);
    //this.success(pluginResult, callbackId);

    return pluginResult;

}

From source file:com.groksolutions.grok.mobile.GrokActivity.java

private void updateRefresh() {
    if (_refresh != null) {
        if (HTMITApplication.isRefreshing()) {
            _refresh.setActionView(_refreshView);

            // Calculate the interval since last connection to the server
            final SharedPreferences pref = PreferenceManager
                    .getDefaultSharedPreferences(getApplicationContext());
            final long now = System.currentTimeMillis();
            final long lastConnected = pref.getLong(PREF_LAST_CONNECTED_TIME, now);
            final long interval = now - lastConnected;

            // Notify the user if the last time we connected was more than one hour ago
            if (interval > DataUtils.MILLIS_PER_HOUR) {
                final long hour = interval / DataUtils.MILLIS_PER_HOUR;
                final long minutes = (interval % DataUtils.MILLIS_PER_HOUR) / DataUtils.MILLIS_PER_MINUTE;
                if (hour > 0) {
                    String title;
                    // Format message: "X hours ago" or "X hours and Y minutes ago"
                    if (minutes > 0) {
                        title = getApplicationContext().getString(R.string.loading_metrics_title_hours_minutes,
                                hour, minutes);
                    } else {
                        title = getApplicationContext().getString(R.string.loading_metrics_title_hours, hour);
                    }//from   ww w .  j  av  a 2 s. c om
                    Toast.makeText(this, title, Toast.LENGTH_LONG).show();
                }
            }
        } else {
            // Check if we have an error message
            String refreshError = HTMITApplication.getLastError();
            if (refreshError == null) {
                // Restore refresh icon
                _refresh.setIcon(R.drawable.ic_action_refresh);
            } else {
                // Show error icon
                _refresh.setIcon(R.drawable.ic_action_connection_error);
            }
            _refresh.setActionView(null);
        }
    }
}

From source file:com.YOMPsolutions.YOMP.mobile.YOMPActivity.java

private void updateRefresh() {
    if (_refresh != null) {
        if (YOMPApplication.isRefreshing()) {
            _refresh.setActionView(_refreshView);

            // Calculate the interval since last connection to the server
            final SharedPreferences pref = PreferenceManager
                    .getDefaultSharedPreferences(getApplicationContext());
            final long now = System.currentTimeMillis();
            final long lastConnected = pref.getLong(PREF_LAST_CONNECTED_TIME, now);
            final long interval = now - lastConnected;

            // Notify the user if the last time we connected was more than one hour ago
            if (interval > DataUtils.MILLIS_PER_HOUR) {
                final long hour = interval / DataUtils.MILLIS_PER_HOUR;
                final long minutes = (interval % DataUtils.MILLIS_PER_HOUR) / DataUtils.MILLIS_PER_MINUTE;
                if (hour > 0) {
                    String title;
                    // Format message: "X hours ago" or "X hours and Y minutes ago"
                    if (minutes > 0) {
                        title = getApplicationContext().getString(R.string.loading_metrics_title_hours_minutes,
                                hour, minutes);
                    } else {
                        title = getApplicationContext().getString(R.string.loading_metrics_title_hours, hour);
                    }/*w w w . j a va2  s  .com*/
                    Toast.makeText(this, title, Toast.LENGTH_LONG).show();
                }
            }
        } else {
            // Check if we have an error message
            String refreshError = YOMPApplication.getLastError();
            if (refreshError == null) {
                // Restore refresh icon
                _refresh.setIcon(R.drawable.ic_action_refresh);
            } else {
                // Show error icon
                _refresh.setIcon(R.drawable.ic_action_connection_error);
            }
            _refresh.setActionView(null);
        }
    }
}

From source file:com.example.android.vault.VaultProvider.java

@Override
public String createDocument(String parentDocumentId, String mimeType, String displayName)
        throws FileNotFoundException {
    final long parentDocId = Long.parseLong(parentDocumentId);

    // Allocate the next available ID
    final long childDocId;
    synchronized (mIdLock) {
        final SharedPreferences prefs = getContext().getSharedPreferences(PREF_NEXT_ID, Context.MODE_PRIVATE);
        childDocId = prefs.getLong(PREF_NEXT_ID, 1);
        if (!prefs.edit().putLong(PREF_NEXT_ID, childDocId + 1).commit()) {
            throw new IllegalStateException("Failed to allocate document ID");
        }/*from  w  w w .j  a v  a2 s .c om*/
    }

    try {
        initDocument(childDocId, mimeType, displayName);

        // Update parent to reference new child
        final EncryptedDocument parentDoc = getDocument(parentDocId);
        final JSONObject parentMeta = parentDoc.readMetadata();
        parentMeta.accumulate(KEY_CHILDREN, childDocId);
        parentDoc.writeMetadataAndContent(parentMeta, null);

        return String.valueOf(childDocId);

    } catch (IOException e) {
        throw new IllegalStateException(e);
    } catch (GeneralSecurityException e) {
        throw new IllegalStateException(e);
    } catch (JSONException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.farmerbb.notepad.fragment.NoteListFragment.java

@Override
public void onStart() {
    super.onStart();

    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, filter);

    // Floating action button
    FloatingActionButton floatingActionButton = getActivity().findViewById(R.id.button_floating_action);
    floatingActionButton.setImageResource(R.drawable.ic_action_new);
    if (getActivity().findViewById(R.id.layoutMain).getTag().equals("main-layout-large"))
        floatingActionButton.hide();/*from   w  w  w.j  a va  2  s  .c  o m*/

    SharedPreferences prefMain = getActivity().getPreferences(Context.MODE_PRIVATE);

    if (getId() == R.id.noteViewEdit && prefMain.getLong("draft-name", 0) == 0) {
        floatingActionButton.show();
        floatingActionButton.setOnClickListener(v -> {
            ScrollPositions.getInstance().setPosition(listView.getFirstVisiblePosition());
            listener.getCabArray().clear();

            Bundle bundle = new Bundle();
            bundle.putString("filename", "new");

            Fragment fragment = new NoteEditFragment();
            fragment.setArguments(bundle);

            // Add NoteEditFragment
            getFragmentManager().beginTransaction().replace(R.id.noteViewEdit, fragment, "NoteEditFragment")
                    .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).commit();
        });
    }
}

From source file:de.linuxwhatelse.android.notify.activities.MainActivity.java

private void handleSnoozedNotification() {
    this.initChannels(this, getString(R.string.notification_channel_snooze));

    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

    boolean notificationsSnoozed = preferences.getBoolean(Notify.PREFERENCE_KEY_NOTIFICATIONS_SNOOZED, false);
    boolean eventsSnoozed = preferences.getBoolean(Notify.PREFERENCE_KEY_EVENTS_SNOOZED, false);
    long snoozeUntil = preferences.getLong(Notify.PREFERENCE_KEY_SNOOZED_UNTIL, -1);

    if (!notificationsSnoozed && !eventsSnoozed) {
        notificationManager.cancel(Notify.NOTIFICATION_ID_SNOOZE);
        return;//from   www .  j  a  v  a 2 s  .c om
    }

    String title = getString(R.string.snoozed_notifications_title);
    if (notificationsSnoozed && eventsSnoozed) {
        title = getString(R.string.snoozed_all_title);
    }

    String body = getString(R.string.snoozed_text_resume_indefinitely);
    if (snoozeUntil != -1) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(snoozeUntil);
        String day = cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault());
        String time = (new SimpleDateFormat("HH:mm", getResources().getConfiguration().locale))
                .format(cal.getTime());

        body = getString(R.string.snoozed_text_resume_at) + " " + day + " " + time;
    }

    Intent activityIntent = new Intent(context, MainActivity.class);
    activityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent activityPendingIntent = PendingIntent.getActivity(context, 0, activityIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, Notify.NOTIFICATION_CHANNEL)
            .setContentTitle(title).setContentText(body).setSmallIcon(R.drawable.ic_notifications_paused)
            .setPriority(NotificationCompat.PRIORITY_LOW).setContentIntent(activityPendingIntent)
            .setOngoing(true);

    Intent intent = new Intent(getApplicationContext(), SnoozeEndReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.drawable.ic_notifications_active,
            getString(R.string.snoozed_action_resume), pendingIntent).build();
    mBuilder.addAction(action);

    notificationManager.notify(Notify.NOTIFICATION_ID_SNOOZE, mBuilder.build());
}

From source file:org.alfresco.mobile.android.application.fragments.preferences.AccountSettingsFragment.java

private void deleteAccount() {
    // List all accounts.
    List<AlfrescoAccount> accounts = AlfrescoAccountManager.retrieveAccounts(getActivity());

    // Remove all Sync
    if (account == null) {
        return;//w  w  w .  j  ava  2  s.co m
    }
    Operator.with(getActivity()).load(new CleanSyncFavoriteRequest.Builder(account, true));

    // Delete Account from AccountManager
    AccountManager.get(getActivity()).removeAccount(
            AlfrescoAccountManager.getInstance(getActivity()).getAndroidAccount(account.getId()), null, null);

    // Analytics
    AnalyticsHelper.reportOperationEvent(getActivity(), AnalyticsManager.CATEGORY_ACCOUNT,
            AnalyticsManager.ACTION_DELETE,
            account.getTypeId() == AlfrescoAccount.TYPE_ALFRESCO_CLOUD ? AnalyticsManager.SERVER_TYPE_CLOUD
                    : AnalyticsManager.SERVER_TYPE_ONPREMISE,
            1, false);

    // In case where currentAccount is the one deleted.
    SessionManager.getInstance(getActivity()).removeAccount(account.getId());

    // Send the event
    EventBusManager.getInstance().post(new DeleteAccountEvent(account));

    AlfrescoAccount newAccount = AlfrescoAccountManager.getInstance(getActivity()).getDefaultAccount();

    if (newAccount != null && newAccount.getId() == account.getId()) {
        SharedPreferences settings = getActivity().getSharedPreferences(AccountsPreferences.ACCOUNT_PREFS, 0);
        long id = settings.getLong(AccountsPreferences.ACCOUNT_DEFAULT, -1);
        if (id == account.getId()) {
            settings.edit().putLong(AccountsPreferences.ACCOUNT_DEFAULT, -1).apply();
        }
    }

    // UI Management
    if (accounts.size() - 1 > 0) {
        for (AlfrescoAccount acc : accounts) {
            if (acc.getId() == account.getId()) {
                accounts.remove(acc);
                break;
            }
        }

        newAccount = accounts.get(0);
        SessionManager.getInstance(getActivity()).saveAccount(newAccount);
        SharedPreferences settings = getActivity().getSharedPreferences(AccountsPreferences.ACCOUNT_PREFS, 0);
        settings.edit().putLong(AccountsPreferences.ACCOUNT_DEFAULT, newAccount.getId()).apply();
        setCurrentAccount(newAccount);

        if (SessionManager.getInstance(getActivity()).hasSession(newAccount.getId())) {
            SessionManager.getInstance(getActivity()).getCurrentSession();
        } else {
            SessionManager.getInstance(getActivity()).loadSession(newAccount);
        }

        // There's still other account.
        // Remove Details panel
        if (DisplayUtils.hasCentralPane(getActivity())) {
            FragmentDisplayer.with(getActivity()).remove(AccountSettingsFragment.TAG);
        } else {
            getFragmentManager().popBackStack(AccountSettingsFragment.TAG,
                    FragmentManager.POP_BACK_STACK_INCLUSIVE);
        }
    } else {
        // If no AlfrescoAccount left, we remove all preferences
        // Remove preferences
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
        sharedPref.edit().clear().apply();

        // Redirect to HomeScreenActivity
        getActivity().startActivity(new Intent(getActivity(), WelcomeActivity.class));
        getActivity().finish();
    }

    // Clear Analytics Info for deleted account
    AnalyticHelper.cleanOpt(getActivity(), account);
}

From source file:org.chromium.chrome.browser.physicalweb.UrlManager.java

/**
 * Gets the time since the last notification update.
 * @return the elapsed realtime since the most recent notification update.
 *//* w  w  w . j  av a 2s  .  co m*/
public long getTimeSinceNotificationUpdate() {
    SharedPreferences prefs = ContextUtils.getAppSharedPreferences();
    long timestamp = prefs.getLong(PREFS_NOTIFICATION_UPDATE_TIMESTAMP, 0);
    return SystemClock.elapsedRealtime() - timestamp;
}

From source file:com.numenta.taurus.TaurusBaseActivity.java

@SuppressLint("AlwaysShowAction")
private void updateRefresh() {
    if (_refresh != null) {
        if (TaurusApplication.isRefreshing()) {
            _refresh.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
            _refresh.setActionView(_refreshView);

            // Calculate the interval since last connection to the server
            final SharedPreferences pref = PreferenceManager
                    .getDefaultSharedPreferences(getApplicationContext());
            final long now = System.currentTimeMillis();
            final long lastConnected = pref.getLong(PREF_LAST_CONNECTED_TIME, now);
            final long interval = now - lastConnected;

            // Notify the user if the last time we connected was more than one hour ago
            if (interval > DataUtils.MILLIS_PER_HOUR) {
                final long hour = interval / DataUtils.MILLIS_PER_HOUR;
                final long minutes = (interval % DataUtils.MILLIS_PER_HOUR) / DataUtils.MILLIS_PER_MINUTE;
                if (hour > 0) {
                    String title;
                    // Format message: "X hours ago" or "X hours and Y minutes ago"
                    if (minutes > 0) {
                        title = getApplicationContext().getString(R.string.loading_metrics_title_hours_minutes,
                                hour, minutes);
                    } else {
                        title = getApplicationContext().getString(R.string.loading_metrics_title_hours, hour);
                    }/*ww  w  .  j  av a  2  s .  co  m*/
                    Toast.makeText(this, title, Toast.LENGTH_LONG).show();
                }
            }
        } else {
            // Check if we have an error message
            String refreshError = TaurusApplication.getLastError();
            if (refreshError == null) {
                _refresh.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
                // Restore refresh icon
                _refresh.setIcon(R.drawable.ic_action_refresh);
            } else {
                _refresh.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
                // Show error icon
                _refresh.setIcon(R.drawable.ic_action_connection_error);
            }
            _refresh.setActionView(null);
        }
    }
}

From source file:com.ijsbrandslob.appirater.Appirater.java

private void loadSettings() {
    SharedPreferences settings = mContext.getSharedPreferences(mContext.getPackageName(), Context.MODE_PRIVATE);

    // Did we save settings before?
    if (settings.contains(APPIRATER_FIRST_USE_DATE)) {
        long firstUseDate = settings.getLong(APPIRATER_FIRST_USE_DATE, -1);
        if (-1 != firstUseDate) {
            mFirstUseDate = new Date(firstUseDate);
        } else {/*from www . j a  v a  2  s. c  om*/
            mFirstUseDate = new Date();
        }

        long reminderRequestDate = settings.getLong(APPIRATER_REMINDER_REQUEST_DATE, -1);
        if (-1 != reminderRequestDate)
            mReminderRequestDate = new Date(reminderRequestDate);

        mUseCount = settings.getInt(APPIRATER_USE_COUNT, 0);
        mSignificantEventCount = settings.getInt(APPIRATER_SIG_EVENT_COUNT, 0);
        mCurrentVersion = settings.getString(APPIRATER_CURRENT_VERSION_NAME, NO_VERSION);
        if (mCurrentVersion == null || mCurrentVersion.equals("")) {
            mCurrentVersion = NO_VERSION;
        }
        mRatedCurrentVersion = settings.getBoolean(APPIRATER_RATED_CURRENT_VERSION, false);
        mDeclinedToRate = settings.getBoolean(APPIRATER_DECLINED_TO_RATE, false);
    } else {
        mCurrentVersion = appVersion();
        mFirstUseDate = new Date();

        if (mConfig.debug)
            System.out.println(String.format("APPIRATER Tracking version: %d", mCurrentVersion));
    }

    if (newAppVersion())
        resetTrackingForNewVersion();
    saveSettings();
}