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.glandorf1.joe.wsprnetviewer.app.sync.WsprNetViewerSyncAdapter.java

private static void notifyWspr(Context context, String bandName, String description, double snr) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String displayNotificationsKey = context.getString(R.string.pref_enable_notifications_key);

    // Get whether notifications are enabled in preferences.
    boolean notificationsEnabled = prefs.getBoolean(displayNotificationsKey,
            Boolean.parseBoolean(context.getString(R.string.pref_enable_notifications_default)));

    if (notificationsEnabled) {
        // Don't notify more often than the user-preference cutoff interval.
        // pref_last_notification is only stored; it is not displayed in the Settings menu.
        // pref_last_notification gets saved below, in editor.putLong(lastNotificationKey, ...).
        long prefMillis = 1000 * (long) Utility.cutoffSeconds(context);
        String lastNotificationKey = context.getString(R.string.pref_last_notification);
        long lastNotification = prefs.getLong(lastNotificationKey, 0);
        Date now = new Date(System.currentTimeMillis());
        Date last = new Date(lastNotification);

        if ((System.currentTimeMillis() - lastNotification) >= prefMillis) {
            // It's been long enough since the last notification; send a new one now.

            int iconId = Utility.getIconResourceForWsprCondition(snr);
            String title = context.getString(R.string.app_name);

            // Define the text of the wspr notification.
            String contentText = String.format(context.getString(R.string.format_notification), description,
                    bandName, Utility.formatSnr(context, snr));

            // NotificationCompatBuilder builds backward-compatible notifications.
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setSmallIcon(iconId)
                    .setContentTitle(title).setContentText(contentText);

            // Open this app if the user clicks on the notification.
            Intent resultIntent = new Intent(context, MainActivity.class);
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
            stackBuilder.addParentStack(MainActivity.class);
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            mBuilder.setContentIntent(resultPendingIntent);
            NotificationManager mNotificationManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            // mId allows you to update the notification later on.
            mNotificationManager.notify(WSPR_NOTIFICATION_ID, mBuilder.build());

            //refreshing last sync
            SharedPreferences.Editor editor = prefs.edit();
            editor.putLong(lastNotificationKey, System.currentTimeMillis());
            editor.commit();//from ww  w  . j a  v a2s . c  o m
        }
    }
}

From source file:org.wso2.iot.agent.proxy.APIController.java

private Token getToken() {
    if (token == null) {
        SharedPreferences mainPref = IdentityProxy.getInstance().getContext()
                .getSharedPreferences(Constants.APPLICATION_PACKAGE, Context.MODE_PRIVATE);
        String refreshToken = mainPref.getString(Constants.REFRESH_TOKEN, null);
        String accessToken = mainPref.getString(Constants.ACCESS_TOKEN, null);
        long expiresOn = mainPref.getLong(Constants.EXPIRE_TIME, 0);
        token = new Token();
        token.setExpiresOn(new Date(expiresOn));
        token.setRefreshToken(refreshToken);
        token.setAccessToken(accessToken);
    }//from  ww  w  .  j a  v a 2s . c o  m
    return token;
}

From source file:com.orange.oidc.secproxy_service.Service.java

long getSecretPathThreshold() {
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    long l = sharedPrefs.getLong("threshold", 80);
    return l;//from  www.  j  ava 2 s  .co m
}

From source file:com.oakonell.dndcharacter.views.character.CharacterActivity.java

@DebugLog
private void loadCharacter(@Nullable Bundle savedInstanceState) {
    long savedId = -1;
    // try to get a character id from
    // 1.   the saved bundle
    if (savedInstanceState != null) {
        savedId = savedInstanceState.getLong(CHARACTER_ID, -1);
    }/*from ww w .  ja  v a  2 s  .  c om*/
    // 2.   the passed intent
    if (savedId == -1 && getIntent().getExtras() != null) {
        savedId = getIntent().getExtras().getLong(CHARACTER_ID, -1);
        if (savedId == -1) {
            if (getIntent().getExtras().getBoolean(CREATE_CHARACTER)) {
                createNewCharacter();
                loading.setVisibility(View.GONE);
                return;
            }
        }
    }
    // 3.   find the last viewed character
    if (savedId == -1) {
        SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
        savedId = sharedpreferences.getLong(CHARACTER_ID, -1);
    }

    if (savedId == -1) {
        createNewCharacter();
        loading.setVisibility(View.GONE);
        return;
    }
    loadCharacter(savedId);

}

From source file:com.entertailion.android.launcher.Dialogs.java

/**
 * Prompt the user to rate the app./*from ww w  .j av a 2 s . co  m*/
 * 
 * @param context
 */
public static void displayRating(final Launcher context) {
    SharedPreferences prefs = context.getSharedPreferences(Launcher.PREFERENCES_NAME, Activity.MODE_PRIVATE);

    if (prefs.getBoolean(DONT_SHOW_RATING_AGAIN, false)) {
        return;
    }

    final SharedPreferences.Editor editor = prefs.edit();

    // Get date of first launch
    Long date_firstLaunch = prefs.getLong(DATE_FIRST_LAUNCHED, 0);
    if (date_firstLaunch == 0) {
        date_firstLaunch = System.currentTimeMillis();
        editor.putLong(DATE_FIRST_LAUNCHED, date_firstLaunch);
    }

    // Wait at least n days before opening
    if (System.currentTimeMillis() >= date_firstLaunch + (DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000)) {
        final Dialog dialog = new Dialog(context);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.confirmation);

        TextView confirmationTextView = (TextView) dialog.findViewById(R.id.confirmationText);
        confirmationTextView.setText(context.getString(R.string.rating_message));
        Button buttonYes = (Button) dialog.findViewById(R.id.button1);
        buttonYes.setText(context.getString(R.string.dialog_yes));
        buttonYes.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse("market://details?id=com.entertailion.android.launcher"));
                context.startActivity(intent);
                if (editor != null) {
                    editor.putBoolean(DONT_SHOW_RATING_AGAIN, true);
                    editor.commit();
                }
                Analytics.logEvent(Analytics.RATING_YES);
                context.showCover(false);
                dialog.dismiss();
            }

        });
        Button buttonNo = (Button) dialog.findViewById(R.id.button2);
        buttonNo.setText(context.getString(R.string.dialog_no));
        buttonNo.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (editor != null) {
                    editor.putBoolean(DONT_SHOW_RATING_AGAIN, true);
                    editor.commit();
                }
                Analytics.logEvent(Analytics.RATING_NO);
                context.showCover(false);
                dialog.dismiss();
            }

        });
        dialog.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface dialog) {
                context.showCover(false);
            }

        });
        context.showCover(true);
        dialog.show();
    }

    editor.commit();
}

From source file:com.amsterdam.marktbureau.makkelijkemarkt.LoginFragment.java

/**
 * Set the login fragment layout and initialize the login logic
 * @param inflater inflater object to inflate the layout
 * @param container the parent view container
 * @param savedInstanceState fragment state bundle
 * @return the inflated view//from   www  .j  av a 2 s .c om
 */
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    // inflate the login fragment layout
    View mainView = inflater.inflate(R.layout.login_fragment, container, false);

    // bind the elements to the view
    ButterKnife.bind(this, mainView);

    if (savedInstanceState == null) {

        // check if there is a newer build of the app available
        Utility.checkForUpdate(getActivity(), UPDATE_FRAGMENT_TAG, true);

        // TODO: if there is no internet connection and accounts were never loaded: keep checking for an internet connection and try again

        // check time in hours since last fetched the accounts
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext());
        long diffInHours = getResources()
                .getInteger(R.integer.makkelijkemarkt_api_accounts_fetch_interval_hours);
        if (settings.contains(getContext().getString(R.string.sharedpreferences_key_accounts_last_fetched))) {
            long lastFetchTimestamp = settings
                    .getLong(getContext().getString(R.string.sharedpreferences_key_accounts_last_fetched), 0);
            long differenceMs = new Date().getTime() - lastFetchTimestamp;
            diffInHours = TimeUnit.MILLISECONDS.toHours(differenceMs);
        }

        // update the local accounts by reloading them from the api
        if (diffInHours >= getResources()
                .getInteger(R.integer.makkelijkemarkt_api_accounts_fetch_interval_hours)) {

            // show the progressbar
            mAccountsProgressBar.setVisibility(View.VISIBLE);

            // call the api
            ApiGetAccounts getAccounts = new ApiGetAccounts(getContext());
            if (!getAccounts.enqueue()) {
                mAccountsProgressBar.setVisibility(View.GONE);
            }
        }
    }

    // create an adapter for the account spinner
    mAccountsAdapter = new SimpleCursorAdapter(getContext(), android.R.layout.simple_list_item_activated_1,
            null, new String[] { MakkelijkeMarktProvider.Account.COL_NAAM }, new int[] { android.R.id.text1 },
            0);

    // attach the adapter to the account spinner
    mAccount.setAdapter(mAccountsAdapter);

    // initiate loading the accounts from the database
    getLoaderManager().initLoader(ACCOUNTS_LOADER, null, this);

    // disable all caps for the button title
    mLoginButton.setTransformationMethod(null);

    // create the login progress dialog
    mLoginProcessDialog = new ProgressDialog(getContext());
    mLoginProcessDialog.setIndeterminate(true);
    mLoginProcessDialog
            .setIndeterminateDrawable(ContextCompat.getDrawable(getContext(), R.drawable.progressbar_circle));
    mLoginProcessDialog.setMessage(getString(R.string.login) + "...");
    mLoginProcessDialog.setCancelable(false);

    return mainView;
}

From source file:com.auth0.android.lock.PasswordlessLockActivity.java

private void reloadRecentPasswordlessData() {
    int choosenMode = configuration.getPasswordlessMode();
    if (choosenMode == PasswordlessMode.DISABLED) {
        return;//from  w w  w .j  a v  a2  s.c  o  m
    }
    SharedPreferences sp = getSharedPreferences(LOCK_PREFERENCES_NAME, Context.MODE_PRIVATE);
    int savedMode = sp.getInt(LAST_PASSWORDLESS_MODE_KEY, PasswordlessMode.DISABLED);
    if (sp.getLong(LAST_PASSWORDLESS_TIME_KEY, 0) + CODE_TTL < System.currentTimeMillis()
            || choosenMode != savedMode) {
        Log.d(TAG, "Previous Passwordless data is too old to reload.");
        return;
    }

    String text = sp.getString(LAST_PASSWORDLESS_EMAIL_NUMBER_KEY, "");
    lastPasswordlessEmailOrNumber = text;
    String countryInfo = sp.getString(LAST_PASSWORDLESS_COUNTRY_KEY, null);
    if (countryInfo != null) {
        String isoCode = countryInfo.split(COUNTRY_DATA_DIV)[0];
        String dialCode = countryInfo.split(COUNTRY_DATA_DIV)[1];
        if (text.startsWith(dialCode)) {
            text = text.substring(dialCode.length());
        }
        lastPasswordlessCountry = new Country(isoCode, dialCode);
    }
    lockView.loadPasswordlessData(text, lastPasswordlessCountry);
}

From source file:com.yeldi.yeldibazaar.UpdateService.java

protected void onHandleIntent(Intent intent) {

    receiver = intent.getParcelableExtra("receiver");

    long startTime = System.currentTimeMillis();
    String errmsg = "";
    try {//from  w ww .  jav  a 2  s  . c o m

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

        // See if it's time to actually do anything yet...
        if (isScheduledRun()) {
            long lastUpdate = prefs.getLong("lastUpdateCheck", 0);
            String sint = prefs.getString("updateInterval", "0");
            int interval = Integer.parseInt(sint);
            if (interval == 0) {
                Log.d("FDroid", "Skipping update - disabled");
                return;
            }
            long elapsed = System.currentTimeMillis() - lastUpdate;
            if (elapsed < interval * 60 * 60 * 1000) {
                Log.d("FDroid",
                        "Skipping update - done " + elapsed + "ms ago, interval is " + interval + " hours");
                return;
            }
        } else {
            Log.d("FDroid", "Unscheduled (manually requested) update");
        }

        boolean notify = prefs.getBoolean("updateNotify", false);

        // Grab some preliminary information, then we can release the
        // database while we do all the downloading, etc...
        int prevUpdates = 0;
        int newUpdates = 0;
        List<DB.Repo> repos;
        try {
            DB db = DB.getDB();
            repos = db.getRepos();
        } finally {
            DB.releaseDB();
        }

        // Process each repo...
        List<DB.App> apps = new ArrayList<DB.App>();
        List<Integer> keeprepos = new ArrayList<Integer>();
        boolean success = true;
        boolean changes = false;
        for (DB.Repo repo : repos) {
            if (repo.inuse) {

                sendStatus(STATUS_INFO, getString(R.string.status_connecting_to_repo, repo.address));

                StringBuilder newetag = new StringBuilder();
                String err = RepoXMLHandler.doUpdate(getBaseContext(), repo, apps, newetag, keeprepos, this);
                if (err == null) {
                    String nt = newetag.toString();
                    if (!nt.equals(repo.lastetag)) {
                        repo.lastetag = newetag.toString();
                        changes = true;
                    }
                } else {
                    success = false;
                    err = "Update failed for " + repo.address + " - " + err;
                    Log.d("FDroid", err);
                    if (errmsg.length() == 0)
                        errmsg = err;
                    else
                        errmsg += "\n" + err;
                }
            }
        }

        List<DB.App> acceptedapps = new ArrayList<DB.App>();
        if (!changes && success) {
            Log.d("FDroid", "Not checking app details or compatibility, because all repos were up to date.");
        } else if (changes && success) {

            sendStatus(STATUS_INFO, getString(R.string.status_checking_compatibility));
            List<DB.App> prevapps = ((FDroidApp) getApplication()).getApps();

            DB db = DB.getDB();
            try {

                // Need to flag things we're keeping despite having received
                // no data about during the update. (i.e. stuff from a repo
                // that we know is unchanged due to the etag)
                for (int keep : keeprepos) {
                    for (DB.App app : prevapps) {
                        boolean keepapp = false;
                        for (DB.Apk apk : app.apks) {
                            if (apk.repo == keep) {
                                keepapp = true;
                                break;
                            }
                        }
                        if (keepapp) {
                            DB.App app_k = null;
                            for (DB.App app2 : apps) {
                                if (app2.id.equals(app.id)) {
                                    app_k = app2;
                                    break;
                                }
                            }
                            if (app_k == null) {
                                apps.add(app);
                                app_k = app;
                            }
                            app_k.updated = true;
                            db.populateDetails(app_k, keep);
                            for (DB.Apk apk : app.apks)
                                if (apk.repo == keep)
                                    apk.updated = true;
                        }
                    }
                }

                prevUpdates = db.beginUpdate(prevapps);
                for (DB.App app : apps) {
                    if (db.updateApplication(app))
                        acceptedapps.add(app);
                }
                db.endUpdate();
                if (notify)
                    newUpdates = db.getNumUpdates();
                for (DB.Repo repo : repos)
                    db.writeLastEtag(repo);
            } catch (Exception ex) {
                db.cancelUpdate();
                Log.e("FDroid", "Exception during update processing:\n" + Log.getStackTraceString(ex));
                errmsg = "Exception during processing - " + ex.getMessage();
                success = false;
            } finally {
                DB.releaseDB();
            }

        }

        if (success) {
            File d = DB.getIconsPath(this);
            List<DB.App> toDownloadIcons = null;
            if (!d.exists()) {
                Log.d("FDroid", "Icons were wiped. Re-downloading all of them.");
                d.mkdirs();
                toDownloadIcons = ((FDroidApp) getApplication()).getApps();
            } else if (changes) {
                toDownloadIcons = acceptedapps;
            }
            if (toDownloadIcons != null) {

                // Create a .nomedia file in the icons directory. For
                // recent Android versions this isn't necessary, because
                // they recognise the cache location. Older versions don't
                // though.
                File f = new File(d, ".nomedia");
                if (!f.exists()) {
                    try {
                        f.createNewFile();
                    } catch (Exception e) {
                        Log.d("FDroid", "Failed to create .nomedia");
                    }
                }

                sendStatus(STATUS_INFO, getString(R.string.status_downloading_icons));
                for (DB.App app : toDownloadIcons)
                    getIcon(app, repos);
            }
        }

        if (success && changes)
            ((FDroidApp) getApplication()).invalidateAllApps();

        if (success && changes && notify && (newUpdates > prevUpdates)) {
            Log.d("FDroid", "Notifying updates. Apps before:" + prevUpdates + ", apps after: " + newUpdates);
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.icon)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon))
                    .setAutoCancel(true).setContentTitle(getString(R.string.fdroid_updates_available));
            Intent notifyIntent = new Intent(this, FDroid.class).putExtra(FDroid.EXTRA_TAB_UPDATE, true);
            if (newUpdates > 1) {
                mBuilder.setContentText(getString(R.string.many_updates_available, newUpdates));

            } else {
                mBuilder.setContentText(getString(R.string.one_update_available));
            }
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(this).addParentStack(FDroid.class)
                    .addNextIntent(notifyIntent);
            PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
            mBuilder.setContentIntent(pendingIntent);
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                    Context.NOTIFICATION_SERVICE);
            mNotificationManager.notify(1, mBuilder.build());
        }

        if (!success) {
            if (errmsg.length() == 0)
                errmsg = "Unknown error";
            sendStatus(STATUS_ERROR, errmsg);
        } else {
            sendStatus(STATUS_COMPLETE);
            Editor e = prefs.edit();
            e.putLong("lastUpdateCheck", System.currentTimeMillis());
            e.commit();
        }

    } catch (Exception e) {
        Log.e("FDroid", "Exception during update processing:\n" + Log.getStackTraceString(e));
        if (errmsg.length() == 0)
            errmsg = "Unknown error";
        sendStatus(STATUS_ERROR, errmsg);
    } finally {
        Log.d("FDroid", "Update took " + ((System.currentTimeMillis() - startTime) / 1000) + " seconds.");
        receiver = null;
    }
}

From source file:org.akvo.flow.activity.SurveyActivity.java

public void spaceLeftOnCard() {
    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        // TODO: more specific warning if card not mounted?
    }//w ww . j a v a  2  s  .  c o m
    // compute space left
    StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
    double sdAvailSize = (double) stat.getAvailableBlocks() * (double) stat.getBlockSize();
    // One binary gigabyte equals 1,073,741,824 bytes.
    // double gigaAvailable = sdAvailSize / 1073741824;
    // One binary megabyte equals 1 048 576 bytes.
    long megaAvailable = (long) Math.floor(sdAvailSize / 1048576.0);

    // keep track of changes
    SharedPreferences settings = getPreferences(MODE_PRIVATE);
    // assume we had space before
    long lastMegaAvailable = settings.getLong("cardMBAvaliable", 101L);
    SharedPreferences.Editor editor = settings.edit();
    editor.putLong("cardMBAvaliable", megaAvailable);
    // Commit the edits!
    editor.commit();

    if (megaAvailable <= 0L) {// All out, OR media not mounted
        // Bounce user
        ViewUtil.showConfirmDialog(R.string.nocardspacetitle, R.string.nocardspacedialog, this, false,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                        finish();
                    }
                });
        return;
    }

    // just issue a warning if we just descended to or past a number on the list
    if (megaAvailable < lastMegaAvailable) {
        for (long l = megaAvailable; l < lastMegaAvailable; l++) {
            if (ConstantUtil.SPACE_WARNING_MB_LEVELS.contains(Long.toString(l))) {
                // display how much space is left
                String s = getResources().getString(R.string.lowcardspacedialog);
                s = s.replace("%%%", Long.toString(megaAvailable));
                ViewUtil.showConfirmDialog(R.string.lowcardspacetitle, s, this, false,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (dialog != null) {
                                    dialog.dismiss();
                                }
                            }
                        }, null);
                return; // only one warning per survey, even of we passed >1 limit
            }
        }
    }
}

From source file:dess15proj5.fau.cs.osr_amos.mobiletimerecording.ui.SelectedProjectFragment.java

/**
 * This method sets the attributes based on the arguments saved in shared preferences.
 *
 * methodtype set method/*ww w  .jav a 2  s.  c o  m*/
 */
private void setArgumentsFromSharedPreferences() {
    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    projectId = sharedPref.getString("project_id", null);
    projectName = sharedPref.getString("project_name", null);
    finalDate = new Date(sharedPref.getLong("final_date", Long.MAX_VALUE));
}