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.koodroid.chicken.KooDroidHelper.java

public void checkForUpdateOnBackgroundThread(final MainActivity activity) {
    if (mAlreadyCheckedForUpdates) {
        return;//  w w  w.  j  a  v  a 2 s  .  c  o  m
    }
    mAlreadyCheckedForUpdates = true;
    new AsyncTask<Void, Void, Void>() {

        @Override
        protected Void doInBackground(Void... params) {
            SharedPreferences prefs = activity.getSharedPreferences(KooDroidHelper.class.getName(),
                    Context.MODE_PRIVATE);
            Random random = new Random();
            long interval = random.nextInt(7) + 3; // [3, 10)
            long timestamp = prefs.getLong("LastCheckTimestamp", 0);
            long now = System.currentTimeMillis();
            if ((now - timestamp < interval * 24 * 60 * 60 * 1000) && !DEBUG) {
                return null;
            }
            prefs.edit().putLong("LastCheckTimestamp", now).commit();
            HttpURLConnection urlConnection = null;
            BufferedReader in = null;
            try {

                URL url = new URL(mUpdateUrl);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setConnectTimeout(60000);
                urlConnection.setReadTimeout(60000);
                urlConnection.setUseCaches(false);
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();
                if (urlConnection.getResponseCode() == 200) {
                    InputStreamReader reader = new InputStreamReader(urlConnection.getInputStream());
                    in = new BufferedReader(reader);
                    StringBuilder response = new StringBuilder();
                    for (String line = in.readLine(); line != null; line = in.readLine()) {
                        response.append(line);
                    }

                    try {
                        JSONObject jsonObj = new JSONObject(response.toString());
                        mLatestVersion = jsonObj.getString("version_code");
                        mDownloadUrl = jsonObj.getString("download_url");
                    } catch (JSONException e) {
                        System.out.println("Json parse error");
                        e.printStackTrace();
                    }
                    //                        
                    //                        JSONTokener jsonParser = new JSONTokener(response.toString());    
                    //                        // ?json?JSONObject    
                    //                        // ??"name" : nextValue"yuanzhifei89"String    
                    //                        JSONObject person = (JSONObject) jsonParser.nextValue();    
                    //                        // ?JSON?    
                    //                        person.getJSONArray("phone");    
                    //                        person.getString("name");    
                    //                        person.getInt("age");    
                    //                        person.getJSONObject("address");    
                    //                        person.getBoolean("married");    
                    //                        
                    //mLatestVersion = response.toString();
                    int versionCode = Integer.valueOf(mLatestVersion);
                    mUpdateAvailable = Integer.valueOf(mLatestVersion) > Integer
                            .valueOf(getPackageVersionCode(activity));
                }
            } catch (Exception e) {
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                    }
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            //maybeShowUpdateDialog(activity);
        }
    }.execute();
}

From source file:org.mozilla.gecko.sync.syncadapter.SyncAdapter.java

/**
 * Backoff./*  w  w w  .j av  a  2  s .  c  om*/
 */
public synchronized long getEarliestNextSync() {
    SharedPreferences sharedPreferences = mContext.getSharedPreferences("sync.prefs.global",
            SHARED_PREFERENCES_MODE);
    return sharedPreferences.getLong(PREFS_EARLIEST_NEXT_SYNC, 0);
}

From source file:org.mozilla.gecko.sync.syncadapter.SyncAdapter.java

public synchronized void extendEarliestNextSync(long next) {
    SharedPreferences sharedPreferences = mContext.getSharedPreferences("sync.prefs.global",
            SHARED_PREFERENCES_MODE);//from   w  ww.j  av  a2s.  c  om
    if (sharedPreferences.getLong(PREFS_EARLIEST_NEXT_SYNC, 0) >= next) {
        return;
    }
    Editor edit = sharedPreferences.edit();
    edit.putLong(PREFS_EARLIEST_NEXT_SYNC, next);
    edit.commit();
}

From source file:it.feio.android.omninotes.async.UpdaterTask.java

@Override
protected Void doInBackground(String... params) {

    String appData = getAppData();
    try {/*w  w  w.ja v a  2 s. c om*/
        // Creation of json object
        JSONObject json = new JSONObject(appData);

        promptUpdate = isVersionUpdated(json.getString("softwareVersion"));

        // Getting from preferences last update check
        @SuppressWarnings("static-access")
        SharedPreferences prefs = mActivity.getSharedPreferences(Constants.PREFS_NAME,
                mActivity.MODE_MULTI_PROCESS);

        long now = System.currentTimeMillis();
        if (promptUpdate
                && now > prefs.getLong(Constants.PREF_LAST_UPDATE_CHECK, 0) + Constants.UPDATE_MIN_FREQUENCY) {
            promptUpdate = true;
            prefs.edit().putLong(Constants.PREF_LAST_UPDATE_CHECK, now).commit();
        } else {
            promptUpdate = false;
        }

    } catch (Exception e) {
        Ln.w(e, "Error fetching app metadata");
    }

    return null;
}

From source file:org.alfresco.mobile.android.application.accounts.AccountManager.java

public Account getDefaultAccount() {
    // Default account to load
    SharedPreferences settings = appContext.getSharedPreferences(AccountsPreferences.ACCOUNT_PREFS, 0);
    long id = settings.getLong(AccountsPreferences.ACCOUNT_DEFAULT, -1);
    //Log.d(TAG, "Default AccountId " + id);
    if (id == -1) {
        return retrieveFirstAccount(appContext);
    } else {//from  w w w  .j ava 2s. com
        return retrieveAccount(appContext, id);
    }
}

From source file:com.sakisds.icymonitor.fragments.graph.GraphContainerFragment.java

protected RequestParams getParameters() {
    RequestParams params = getParametersWithoutId();
    SharedPreferences prefs = getActivity().getSharedPreferences(MainViewActivity.SHAREDPREFS_FILE, 0);

    params.put("id", String.valueOf(prefs.getLong("device_id", -2)));

    return params;
}

From source file:com.numenta.taurus.service.TaurusDataSyncService.java

/**
 * Load all instance data from the database
 *//*from   www.  jav  a 2  s  .  c om*/
@Override
protected void loadAllData() throws HTMException, IOException {

    Context context = TaurusApplication.getContext();
    if (context == null) {
        // Should not happen.
        // We need application context to run.
        return;
    }

    // Get last known date from the database
    final TaurusDatabase database = TaurusApplication.getDatabase();
    if (database == null) {
        // Should not happen.
        // We need application context to run.
        return;
    }
    long from = database.getLastTimestamp();

    // Get current time
    final long now = System.currentTimeMillis();

    // The server updates the instance data table into hourly buckets as the models process
    // data. This may leave the last hour with outdated values when the server updates the
    // instance data table after we start loading the new hourly bucket.
    // To make sure the last hour bucket is updated we should get data since last update up to
    // now and on when the time is above a certain threshold (15 minutes) also download the
    // previous hour once.
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    // Check if we need to update the previous hour
    long previousHourThreshold = prefs.getLong(PREF_PREVIOUS_HOUR_THRESHOLD, now);
    if (now >= previousHourThreshold) {
        // Download the previous hour
        from -= DataUtils.MILLIS_PER_HOUR;

        // Set threshold time to minute 15 of next hour
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(now);
        calendar.add(Calendar.HOUR, 1);
        calendar.set(Calendar.MINUTE, 15);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        prefs.edit().putLong(PREF_PREVIOUS_HOUR_THRESHOLD, calendar.getTimeInMillis()).apply();
    }
    final long oldestTimestamp = DataUtils
            .floorTo60minutes(now - TaurusApplication.getNumberOfDaysToSync() * DataUtils.MILLIS_PER_DAY);

    // Check if we need to catch up and download old data
    if (database.getFirstTimestamp() > oldestTimestamp) {
        from = oldestTimestamp;
    }

    // Don't get date older than NUMBER_OF_DAYS_TO_SYNC
    from = Math.max(from, oldestTimestamp);

    // Blocking queue holding data waiting to be saved to the database.
    // This queue will be filled by the TaurusClient as it downloads data and it will be
    // emptied by the databaseTask as is saves data to the database
    final LinkedBlockingQueue<InstanceData> pending = new LinkedBlockingQueue<InstanceData>(
            PENDING_IO_BUFFER_SIZE);

    // Background task used save data to the database. This task will wait for data to arrive
    // from the server and save them to the database in batches until it finds the end of the
    // queue marked by DATA_EOF or it times out after 60 seconds
    final Future<?> databaseTask = getService().getIOThreadPool().submit(new Runnable() {
        @Override
        public void run() {
            // Save data in batches, one day at the time
            final List<InstanceData> batch = new ArrayList<InstanceData>();
            int batchSize = -DataUtils.MILLIS_PER_HOUR;

            // Tracks batch timestamp. Once the data timestamp is greater than the batch
            // timestamp, a new batch is created
            long batchTimestamp = now - DataUtils.MILLIS_PER_HOUR;

            try {
                // Process all pending data until the DATA_EOF is found or a timeout is reached
                InstanceData data;
                while ((data = pending.poll(60, TimeUnit.SECONDS)) != DATA_EOF && data != null) {
                    batch.add(data);
                    // Process batches
                    if (data.getTimestamp() < batchTimestamp) {
                        // Calculate next batch timestamp
                        batchTimestamp = data.getTimestamp() + batchSize;
                        if (database.addInstanceDataBatch(batch)) {
                            // Notify receivers new data has arrived
                            fireInstanceDataChangedEvent();
                        }
                        batch.clear();
                    }
                }
                // Last batch
                if (!batch.isEmpty()) {
                    if (database.addInstanceDataBatch(batch)) {
                        // Notify receivers new data has arrived
                        fireInstanceDataChangedEvent();
                    }
                }
            } catch (InterruptedException e) {
                Log.w(TAG, "Interrupted while loading data");
            }
        }
    });

    try {
        // Get new data from server
        Log.d(TAG, "Start downloading data from " + from);
        TaurusClient client = getClient();
        client.getAllInstanceData(new Date(from), new Date(now), false,
                new HTMClient.DataCallback<InstanceData>() {
                    @Override
                    public boolean onData(InstanceData data) {
                        // enqueue data for saving
                        try {
                            pending.put(data);
                        } catch (InterruptedException e) {
                            pending.clear();
                            Log.w(TAG, "Interrupted while loading data");
                            return false;
                        }
                        return true;
                    }
                });
        // Mark the end of the records
        pending.add(DATA_EOF);
        // Wait for the database task to complete
        databaseTask.get();
        // Clear client cache
        client.clearCache();
    } catch (InterruptedException e) {
        Log.w(TAG, "Interrupted while loading data");
    } catch (ExecutionException e) {
        Log.e(TAG, "Failed to load data", e);
    }
}

From source file:nz.co.wholemeal.christchurchmetro.FavouritesActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.favourites_list);

    if (stops.size() == 0) {
        initFavourites();/*from   w ww . j  a  v a 2  s  .c o  m*/
    }

    stopAdapter = new StopAdapter(this, R.layout.stop_list_item, stops);
    setListAdapter(stopAdapter);

    ListView lv = getListView();

    /* Enables the long click in the ListView to be handled in this Activity */
    registerForContextMenu(lv);

    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent();
            Stop stop = (Stop) stops.get(position);

            if (stop == null) {
                Log.e(TAG, "Didn't get a stop");
                finish();
            }
            intent.putExtra("platformTag", stop.platformTag);
            intent.setClassName("nz.co.wholemeal.christchurchmetro",
                    "nz.co.wholemeal.christchurchmetro.PlatformActivity");

            startActivity(intent);
        }
    });

    /*
     * This will contain return non null if we received an orientation change
     */
    asyncLoadPlatforms = (AsyncLoadPlatforms) getLastNonConfigurationInstance();
    if (asyncLoadPlatforms != null) {
        loadDataDialogShown = true;
        initProgressDialog();
        asyncLoadPlatforms.attach(this);
    }

    SharedPreferences preferences = getSharedPreferences(PlatformActivity.PREFERENCES_FILE, 0);
    if (preferences.getLong("lastDataLoad", -1) == -1 && !loadDataDialogShown) {
        showDialog(DIALOG_LOAD_DATA);
    }
}

From source file:org.arasthel.almeribus.Principal.java

@Override
public void onPostCreate(Bundle savedInstanceState) {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    long ultimaActualizacion = sp.getLong("ultima_actualizacion", 0);
    Date fechaUltima = new Date(ultimaActualizacion);
    long nuevoTiempo = System.currentTimeMillis();
    Date nuevaFecha = new Date(nuevoTiempo);

    necesitaActualizacion = false;/*from  ww  w  .ja v a 2s.  c o  m*/

    if (nuevaFecha.getDay() != fechaUltima.getDay() || nuevaFecha.getMonth() != fechaUltima.getMonth()
            || nuevaFecha.getYear() != fechaUltima.getYear()) {
        necesitaActualizacion = true;
    }

    // We load the bus stop info from Surbus server
    cargarParadas();
    if (savedInstanceState == null && !necesitaActualizacion && !loaded) {
        savedInstanceState = new Bundle();
        savedInstanceState.putBoolean("SlidingActivityHelper.open", true);
    }
    super.onPostCreate(savedInstanceState);
}

From source file:de.tu_darmstadt.kom.freifunkfinder.user_interface.MainActivity.java

/**
 * MainActivity's.onCreate method, set listeners of all configurable items.
 *
 * @param savedInstanceState Saved instance state bundle.
 *//*from w  w w  .  j a v a  2  s  .  c o m*/
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // shared pref operation
    SharedPreferences sharedPreferences = getSharedPreferences(FreifunkFinderAppConstants.PREFS_TIMESTAMP, 0);
    long oldTimestamp = sharedPreferences.getLong(FreifunkFinderAppConstants.PREFERENC_KEY, 0L);
    Log.d(DEBUG_TAG, "Old timestamp received = " + oldTimestamp);
    GlobalParams.setOldTimeStamp(oldTimestamp);

    /*<<<<<<< HEAD:app/src/main/java/de/tu_darmstadt/kom/freifunkfinder/user_interface/MainActivity.java
            //Initialize toolbar options
    =======
            
    >>>>>>> debf605494804f586b7d98939b55c59832800612:src/main/java/de/tu_darmstadt/kom/freifunkfinder/user_interface/MainActivity.java
    */ Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(false);

    //Set loading progressbar invisible on startup
    progressBar = (ProgressBar) findViewById(R.id.progress_bar);
    progressBar.setVisibility(View.INVISIBLE);
    progressBarTxt = (TextView) findViewById(R.id.progress_bar_txt);
    progressBarTxt.setVisibility(View.INVISIBLE);

    //MobileLocationManageer instantiation
    mobileLocationManager = new MobileLocationManager(getApplicationContext(), MainActivity.this);
    mobileLocationManager.initLocation();

    //WifiFinderApplication instantiation
    wifiFinderApplication = WifiFinderApplication.getWifiFinderApplication(getApplicationContext());

    //JSON read, need location info for this
    JsonReaderAsyncTask jsonReaderAsyncTask = new JsonReaderAsyncTask();
    jsonReaderAsyncTask.execute();

    //WifiOverlay instantiation
    wifiOverlayView = new WifiOverlayView(getApplicationContext(), this, mobileLocationManager);

    //CameraView instantiation
    cameraView = new CameraView(getApplicationContext(), MainActivity.this);

    //FrameLayout instantiation
    arView = (FrameLayout) findViewById(R.id.ar_view);
    button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            arView.addView(cameraView);
            arView.addView(wifiOverlayView);
            view.setVisibility(View.INVISIBLE);
            if (!GlobalParams.isWifiNodesPersisted()) {
                progressBar.setVisibility(View.VISIBLE);
                progressBarTxt.setVisibility(View.VISIBLE);
            }
            isOverlayView = true;
        }
    });

    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();
    drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    final TextView seekTextView = (TextView) findViewById(R.id.seekTextView);

    //seek bar listener for saving user selected distance
    final SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar);
    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        int distance;
        Double lookupDistance = 999.000;

        @Override
        public void onProgressChanged(SeekBar seekBar, int progresValue, boolean fromUser) {
            isParamChanged = true;
            distance = (progresValue * 2000 / seekBar.getMax());
            GlobalParams.setSearchRange(distance);
            lookupDistance = (distance < 999 ? ((double) distance) : (distance / 1000.00));
            seekTextView.setText("Distnce : " + String.format("%.2f", lookupDistance) + " "
                    + (distance < 999 ? "Meters" : "Kilometers"));
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            isParamChanged = true;
            distance = (seekBar.getProgress() * 2000 / seekBar.getMax());
            GlobalParams.setSearchRange(distance);
            lookupDistance = (distance < 999 ? ((double) distance) : (distance / 1000.00));
            seekTextView.setText("Distnce : " + String.format("%.2f", lookupDistance) + " "
                    + (distance < 999 ? "Meters" : "Kilometers"));
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            isParamChanged = true;
            distance = (seekBar.getProgress() * 2000 / seekBar.getMax());
            GlobalParams.setSearchRange(distance);
            lookupDistance = (distance < 999 ? ((double) distance) : (distance / 1000.00));
            seekTextView.setText("Distnce : " + String.format("%.2f", lookupDistance) + " "
                    + (distance < 999 ? "Meters" : "Kilometers"));
        }
    });

    //Edit textr listener for saving user selected count
    final EditText editText = (EditText) findViewById(R.id.countView);
    editText.addTextChangedListener(new TextWatcher() {
        int count;

        public void afterTextChanged(Editable s) {
            isParamChanged = true;

            if (!editText.getText().toString().equals("")) {
                count = Integer.parseInt(editText.getText().toString());
                GlobalParams.setNodesCount(count);
            } else {
                GlobalParams.setNodesCount(10);
            }
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });
}