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.kobi.metalsexchange.app.MainActivity.java

private void updateTheLastUpdatedTime() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    long lastUpdatedVal = prefs.getLong("LAST_UPDATED", 0);
    if (lastUpdatedVal > 0) {
        mLastUpdatedTextView.setText(Utility.getFriendlyDayTimeString(this, lastUpdatedVal));
    }//from ww w.ja v a  2 s .  com
}

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

public void significantEvent() {
    boolean testMode = mContext.getResources().getBoolean(R.bool.appirator_test_mode);
    SharedPreferences prefs = mContext.getSharedPreferences(mContext.getPackageName() + ".appirater", 0);
    if (!testMode && (prefs.getBoolean(PREF_DONT_SHOW, false) || prefs.getBoolean(PREF_RATE_CLICKED, false))) {
        return;//from w  ww . j  a v  a  2  s  . c om
    }
    long event_count = prefs.getLong(PREF_EVENT_COUNT, 0);
    event_count++;
    prefs.edit().putLong(PREF_EVENT_COUNT, event_count).commit();
}

From source file:org.catrobat.catroid.ui.ScratchConverterActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scratch_converter);
    setUpActionBar();//  ww w . java2 s . c o m
    setReturnByPressingBackButton(true);

    searchProjectsListFragment = (SearchScratchSearchProjectsListFragment) getFragmentManager()
            .findFragmentById(R.id.fragment_scratch_search_projects_list);
    searchProjectsListFragment.setDataFetcher(dataFetcher);
    converterSlidingUpPanelFragment = (ScratchConverterSlidingUpPanelFragment) getFragmentManager()
            .findFragmentById(R.id.fragment_scratch_converter_sliding_up_panel);

    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    final long clientID = settings.getLong(Constants.SCRATCH_CONVERTER_CLIENT_ID_SHARED_PREFERENCE_NAME,
            Client.INVALID_CLIENT_ID);

    if (client == null) {
        client = new WebSocketClient(clientID, new WebSocketMessageListener());
    }

    conversionManager = new ScratchConversionManager(this, client, false);
    conversionManager.setCurrentActivity(this);
    conversionManager.addGlobalDownloadCallback(converterSlidingUpPanelFragment);
    conversionManager.addBaseInfoViewListener(converterSlidingUpPanelFragment);
    conversionManager.addGlobalJobViewListener(converterSlidingUpPanelFragment);
    searchProjectsListFragment.setConversionManager(conversionManager);

    slidingLayout = (SlidingUpPanelLayout) findViewById(R.id.sliding_layout);
    slidingLayout.addPanelSlideListener(this);

    final int betaLabelColor = ContextCompat.getColor(this, R.color.beta_label_color);
    appendColoredBetaLabelToTitle(betaLabelColor);
    hideSlideUpPanelBar();
    Log.i(TAG, "Scratch Converter Activity created");
}

From source file:org.jboss.aerogear.android.unifiedpush.gcm.AeroGearGCMPushRegistrar.java

/**
 * Checks if the registration has expired.
 * /*from   w w w  .  ja v a  2s  .  co  m*/
 * To avoid the scenario where the device sends the registration to the
 * server but the server loses it, the app developer may choose to
 * re-register after REGISTRATION_EXPIRY_TIME_MS.
 * 
 * @return true if the registration has expired.
 */
private boolean isRegistrationExpired(Context context) {
    final SharedPreferences prefs = getGCMPreferences(context);
    // checks if the information is not stale
    long expirationTime = prefs.getLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, -1);
    return System.currentTimeMillis() > expirationTime;
}

From source file:it.polimi.spf.demo.couponing.client.CategoryFragment.java

private void deleteCategory(String category) {
    if (mNotificationService == null) {
        toast(R.string.error_notification_service_unavailable);
        return;//  w w  w  . j  av a  2  s .  co m
    }

    SharedPreferences pf = getPreferences();
    long triggerId = pf.getLong(category, -1);
    if (!mNotificationService.deleteTrigger(triggerId)) {
        toast(R.string.error_cannot_delete_trigger);
        //return;
    }

    getPreferences().edit().remove(category).apply();
}

From source file:com.nextgis.firereporter.ReporterService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "Received start id " + startId + ": " + intent);
    super.onStartCommand(intent, flags, startId);

    if (intent == null)
        return START_STICKY;
    String action = intent.getAction();
    if (action.equals(ACTION_STOP)) {
        this.stopSelf();
    } else if (action.equals(ACTION_START)) {
        Log.d(TAG, "Action " + ACTION_START);
        Context c = this.getApplicationContext();
        SharedPreferences prefs = getSharedPreferences(MainActivity.PREFERENCES,
                MODE_PRIVATE | MODE_MULTI_PROCESS);
        long nMinTimeBetweenSend = prefs.getLong(SettingsActivity.KEY_PREF_INTERVAL + "_long",
                DateUtils.MINUTE_IN_MILLIS);
        boolean bBattEconomy = prefs.getBoolean(SettingsActivity.KEY_PREF_SERVICE_BATT_SAVE, true);

        if (!HttpGetter.IsNetworkAvailible(c)) {
            ScheduleNextUpdate(c, nMinTimeBetweenSend, bBattEconomy);
            Log.d(TAG, "network not availible");
            return START_NOT_STICKY;
        }//from  ww w .j a  v  a2s  .  c o m

        Cursor cursor = ReportsDB.query(ReportsDatabase.TABLE_POS, null, null, null, null, null, null);
        Log.d(TAG, "record count = " + cursor.getCount());
        if (cursor.getCount() < 1) {
            this.stopSelf();
            return START_NOT_STICKY;
        }

        if (fireDataSender == null) {
            Log.d(TAG, "new fireDataSender");
            fireDataSender = new SendFireDataTask();
            fireDataSender.execute(this.getApplicationContext());
            ScheduleNextUpdate(c, nMinTimeBetweenSend, bBattEconomy);
        } else if (fireDataSender.getStatus() == AsyncTask.Status.FINISHED) {
            Log.d(TAG, "exist fireDataSender");
            fireDataSender.execute(this.getApplicationContext());
            ScheduleNextUpdate(c, nMinTimeBetweenSend, bBattEconomy);
        } else if (fireDataSender.getStatus() == AsyncTask.Status.PENDING
                || fireDataSender.getStatus() == AsyncTask.Status.RUNNING) {
            Log.d(TAG, "exist fireDataSender executing");
            ScheduleNextUpdate(c, nMinTimeBetweenSend, bBattEconomy);
        } else {
            Log.d(TAG, "unexpected behaviour");
            this.stopSelf();
        }
    }
    return START_NOT_STICKY;
}

From source file:com.svpino.longhorn.MarketCollectorService.java

@Override
protected void onHandleIntent(Intent intent) {
    SharedPreferences sharedPreferences = getSharedPreferences(Constants.PREFERENCES, Context.MODE_PRIVATE);
    long lastUpdate = sharedPreferences.getLong(Constants.PREFERENCE_COLLECTOR_LAST_UPDATE, 0);
    boolean retrying = sharedPreferences.getBoolean(Constants.PREFERENCE_COLLECTOR_RETRYING, false);
    int retries = sharedPreferences.getInt(Constants.PREFERENCE_COLLECTOR_RETRIES, 0);
    boolean wereWeWaitingForConnectivity = sharedPreferences
            .getBoolean(Constants.PREFERENCE_STATUS_WAITING_FOR_CONNECTIVITY, false);

    boolean isGlobalCollection = intent.getExtras() == null
            || (intent.getExtras() != null && !intent.getExtras().containsKey(EXTRA_TICKER));

    if (wereWeWaitingForConnectivity) {
        Editor editor = sharedPreferences.edit();
        editor.putBoolean(Constants.PREFERENCE_STATUS_WAITING_FOR_CONNECTIVITY, false);
        editor.commit();/* ww w . j av  a2  s .c  o m*/
    }

    if (retrying && isGlobalCollection) {
        Editor editor = sharedPreferences.edit();
        editor.putBoolean(Constants.PREFERENCE_COLLECTOR_RETRYING, false);
        editor.putInt(Constants.PREFERENCE_COLLECTOR_RETRIES, 0);
        editor.commit();

        ((AlarmManager) getSystemService(Context.ALARM_SERVICE))
                .cancel(Extensions.createPendingIntent(this, Constants.SCHEDULE_RETRY));
    }

    long currentTime = System.currentTimeMillis();
    if (retrying || wereWeWaitingForConnectivity || !isGlobalCollection
            || (isGlobalCollection && currentTime - lastUpdate > Constants.COLLECTOR_MIN_REFRESH_INTERVAL)) {
        String[] tickers = null;

        if (isGlobalCollection) {
            Log.d(LOG_TAG, "Executing global market information collection...");
            tickers = DataProvider.getStockDataTickers(this);
        } else {
            String ticker = intent.getExtras().containsKey(EXTRA_TICKER)
                    ? intent.getExtras().getString(EXTRA_TICKER)
                    : null;

            Log.d(LOG_TAG, "Executing market information collection for ticker " + ticker + ".");

            tickers = new String[] { ticker };
        }

        try {
            collect(tickers);

            if (isGlobalCollection) {
                Editor editor = sharedPreferences.edit();
                editor.putLong(Constants.PREFERENCE_COLLECTOR_LAST_UPDATE, System.currentTimeMillis());
                editor.commit();
            }

            DataProvider.notifyDataCollectionIsFinished(this, tickers);

            Log.d(LOG_TAG, "Market information collection was successfully completed");
        } catch (Exception e) {
            Log.e(LOG_TAG, "Market information collection failed.", e);

            if (Extensions.areWeOnline(this)) {
                Log.d(LOG_TAG, "Scheduling an alarm for retrying a global market information collection...");

                retries++;

                Editor editor = sharedPreferences.edit();
                editor.putBoolean(Constants.PREFERENCE_COLLECTOR_RETRYING, true);
                editor.putInt(Constants.PREFERENCE_COLLECTOR_RETRIES, retries);
                editor.commit();

                long interval = Constants.COLLECTOR_MIN_RETRY_INTERVAL * retries;
                if (interval > Constants.COLLECTOR_MAX_REFRESH_INTERVAL) {
                    interval = Constants.COLLECTOR_MAX_REFRESH_INTERVAL;
                }

                ((AlarmManager) getSystemService(Context.ALARM_SERVICE)).set(AlarmManager.RTC,
                        System.currentTimeMillis() + interval,
                        Extensions.createPendingIntent(this, Constants.SCHEDULE_RETRY));
            } else {
                Log.d(LOG_TAG,
                        "It appears that we are not online, so let's start listening for connectivity updates.");

                Editor editor = sharedPreferences.edit();
                editor.putBoolean(Constants.PREFERENCE_STATUS_WAITING_FOR_CONNECTIVITY, true);
                editor.commit();

                ComponentName componentName = new ComponentName(this, ConnectivityBroadcastReceiver.class);
                getPackageManager().setComponentEnabledSetting(componentName,
                        PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
            }
        }
    } else if (isGlobalCollection && currentTime - lastUpdate <= Constants.COLLECTOR_MIN_REFRESH_INTERVAL) {
        Log.d(LOG_TAG, "Global market information collection will be skipped since it was performed less than "
                + (Constants.COLLECTOR_MIN_REFRESH_INTERVAL / 60 / 1000) + " minutes ago.");
    }

    stopSelf();
}

From source file:com.asksven.betterbatterystats.data.KbReader.java

public KbData read(Context ctx) {
    if (LogSettings.DEBUG) {
        Log.i(TAG, "read called");
    }//from   ww w . j ava  2s  . c o m
    if (m_cache == null) {
        if (LogSettings.DEBUG) {
            Log.i(TAG, "Cache is empty");
        }
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);

        // first check if cache is present and not outdated
        KbDbHelper myDB = KbDbHelper.getInstance(ctx);

        List<KbEntry> myEntries = myDB.fetchAllRows();

        // if cache exists and is not outdaten use it
        long cachedMillis = sharedPrefs.getLong("cache_updated", 0);
        long dateMillis = Calendar.getInstance().getTimeInMillis();
        boolean useCaching = sharedPrefs.getBoolean("cache_kb", true);

        // if cache is not empty, cache not older than 24 hours and caching is on
        if ((myEntries != null) && (myEntries.size() > 0) && (useCaching)
                && ((dateMillis - cachedMillis) < MAX_CACHE_AGE_MILLIS)) {
            m_cache = new KbData();
            m_cache.setEntries(myEntries);
        } else {
            if (LogSettings.DEBUG) {
                Log.i(TAG, "Starting service to retrieve KB");
            }
            // start async service to retrieve KB if not already running
            if (!KbReaderService.isTransactional()) {
                Intent serviceIntent = new Intent(ctx, KbReaderService.class);
                ctx.startService(serviceIntent);
            }
        }
    } else {
        if (LogSettings.DEBUG) {
            Log.i(TAG, "returning cached KB");
        }
    }
    return m_cache;
}

From source file:com.careme.apvereda.careme.AccumulatorService.java

private void monitor(Location loc) {
    // We suppose the user can move 200m in 5 minutes
    SharedPreferences shared = getApplicationContext().getSharedPreferences("monitor", Context.MODE_PRIVATE);
    Date date = new Date();
    date.setTime(shared.getLong("date", 0));
    Date act = new Date();
    if (act.getTime() - date.getTime() > 900000) {
        SharedPreferences.Editor editor = shared.edit();
        editor.putInt("measurements", 0);
        editor.commit();//from   www .  j av a 2s.  c o m
    }
    if (act.getTime() - date.getTime() > 300000) {
        int measurements = shared.getInt("measurements", 0);
        if (measurements >= 6) {
            // Walking, update the list
            updateList(loc);
        } else {
            // Has stopped, reset the list
            resetList(loc);
        }
        // Update the date
        SharedPreferences.Editor editor = shared.edit();
        act = new Date();
        editor.putLong("date", act.getTime());
        editor.commit();
    } else {
        int measurements = shared.getInt("measurements", 0);
        SharedPreferences.Editor editor = shared.edit();
        editor.putInt("measurements", measurements + 1);
        editor.commit();
    }

}

From source file:io.rapidpro.androidchannel.HomeActivity.java

public void updateLastSync(UpdatingTextView view) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    if (RapidPro.get().isClaimed()) {
        long lastUpdate = prefs.getLong(RapidProAlarmListener.LAST_SYNC_TIME, 0);
        if (lastUpdate == 0) {
            view.setText("Waiting..");
        } else {/*from  www.j  a  v a  2s.c om*/
            view.setText(DateUtil.getFuzzyTime(lastUpdate));
        }
        view.setVisibility(View.VISIBLE);
    } else {
        view.setVisibility(View.GONE);
    }
}