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.nextgis.woody.fragment.MapFragment.java

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

    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());

    if (null != mMap && !mShowSelectLocation) {
        if (prefs.getBoolean(SettingsConstants.KEY_PREF_MAP_FIRST_VIEW, true)) {
            // Zoom to trees extent
            MapDrawable md = mMap.getMap();
            ILayer layer = md.getLayerByName(Constants.KEY_MAIN);
            if (layer instanceof VectorLayer) {
                VectorLayer vectorLayer = (VectorLayer) layer;
                mMap.zoomToExtent(vectorLayer.getExtents());
            }/*w w w. ja va2 s .c o  m*/

            final SharedPreferences.Editor edit = prefs.edit();
            edit.putBoolean(SettingsConstants.KEY_PREF_MAP_FIRST_VIEW, false);
            edit.commit();
        } else {
            float mMapZoom;
            try {
                mMapZoom = prefs.getFloat(SettingsConstants.KEY_PREF_ZOOM_LEVEL, mMap.getMinZoom());
            } catch (ClassCastException e) {
                mMapZoom = mMap.getMinZoom();
            }

            double mMapScrollX;
            double mMapScrollY;
            try {
                mMapScrollX = Double.longBitsToDouble(prefs.getLong(SettingsConstants.KEY_PREF_SCROLL_X, 0));
                mMapScrollY = Double.longBitsToDouble(prefs.getLong(SettingsConstants.KEY_PREF_SCROLL_Y, 0));
            } catch (ClassCastException e) {
                mMapScrollX = 0;
                mMapScrollY = 0;
            }
            mMap.setZoomAndCenter(mMapZoom, new GeoPoint(mMapScrollX, mMapScrollY));
        }
        mMap.addListener(this);
    }

    resumeGps();

    mCurrentCenter = null;
}

From source file:org.pixmob.droidlink.sync.SyncAdapter.java

private void doPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {/*from w w w  .ja v  a  2 s  . c o  m*/
    final SharedPreferences prefs = getContext().getSharedPreferences(SHARED_PREFERENCES_FILE,
            Context.MODE_PRIVATE);

    final String lastSyncToken = prefs.getString(SP_KEY_SYNC_TOKEN, null);
    final String syncToken = extras.getString(EventsContract.SYNC_TOKEN);
    if (DEVELOPER_MODE) {
        Log.d(TAG, "Sync token: " + syncToken + "; last sync token: " + lastSyncToken);
    }

    if (lastSyncToken != null && lastSyncToken.equals(syncToken)) {
        Log.w(TAG, "Skip synchronization since this device is already synchronized");
        return;
    }

    // Make sure this sync is about our user.
    final String accountName = prefs.getString(SP_KEY_ACCOUNT, null);
    if (!account.type.equals("com.google") || !account.name.equals(accountName)) {
        if (DEVELOPER_MODE) {
            Log.i(TAG, "Skip sync for user account " + account.name + "/" + account.type);
        }
        return;
    }

    // Check if a synchronization was just made: do not run twice.
    final long lastSync = prefs.getLong(SP_KEY_LAST_SYNC, 0);
    if (System.currentTimeMillis() - lastSync < 1000) {
        Log.w(TAG, "Skip synchronization for user account " + account.name + " since it has just ran");
        return;
    }

    // Check if a network client can be created
    // (a device identifier is required).
    final NetworkClient client = NetworkClient.newInstance(getContext());
    if (client == null) {
        Log.w(TAG, "Failed to create NetworkClient: cannot sync");
        syncResult.stats.numAuthExceptions++;
        return;
    }

    Log.i(TAG, "Start synchronization for user " + accountName);

    final boolean fullSync = extras.getInt(EventsContract.SYNC_STRATEGY,
            EventsContract.FULL_SYNC) == EventsContract.FULL_SYNC;
    if (fullSync) {
        Log.i(TAG, "Performing FULL sync");
    } else {
        Log.i(TAG, "Performing LIGHT sync");
    }

    // Notify that synchronization is starting.
    Intent syncIntent = new Intent(ACTION_SYNC);
    syncIntent.putExtra(EXTRA_RUNNING, true);
    getContext().sendStickyBroadcast(syncIntent);

    try {
        doPerformSync(client, prefs, provider, syncResult, fullSync);
    } finally {
        client.close();

        // Notify synchronization end.
        syncIntent.putExtra(EXTRA_RUNNING, false);
        getContext().sendStickyBroadcast(syncIntent);

        Log.i(TAG, "Synchronization done for user " + accountName);
    }
}

From source file:br.com.indigo.android.facebook.SocialFacebook.java

private void loadLoginInfo() {
    // Retrieve authorization information
    SharedPreferences prefs = mAppContext.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
    mFacebook.setAccessToken(prefs.getString(TOKEN, null));
    mFacebook.setAccessExpires(prefs.getLong(EXPIRES, 0));
}

From source file:com.tweetlanes.android.view.TweetFeedFragment.java

private TwitterStatus getVisibleStatus() {

    TwitterStatus visibleStatus = null;// w  ww.ja v a  2  s . co m

    if (getStatusFeed() != null && mTweetFeedListView != null
            && mTweetFeedListView.getRefreshableView() != null) {
        int visiblePosition = mTweetFeedListView.getRefreshableView().getFirstVisiblePosition();

        if (visiblePosition < getStatusFeed().getStatusCount()) {
            visibleStatus = getStatusFeed().getStatus(visiblePosition);
            if (visibleStatus != null) {
                if (getLaneIndex() == getApp().getCurrentAccount()
                        .getCurrentLaneIndex(Constant.LaneType.USER_MENTIONS)) {
                    SharedPreferences preferences = PreferenceManager
                            .getDefaultSharedPreferences(getBaseLaneActivity());
                    long lastDisplayedMentionId = preferences
                            .getLong(Notifier.SHARED_PREFERENCES_KEY_NOTIFICATION_LAST_DISPLAYED_MENTION_ID
                                    + getApp().getCurrentAccountKey(), 0);

                    if (visibleStatus.mId >= lastDisplayedMentionId) {
                        Notifier.saveLastNotificationActioned(getBaseLaneActivity(),
                                getApp().getCurrentAccountKey(), visibleStatus.mId);
                        Notifier.cancel(getBaseLaneActivity(), getApp().getCurrentAccountKey());
                    }
                }
            }
        }
    }

    return visibleStatus;
}

From source file:com.limewoodmedia.nsdroid.services.UpdateService.java

@Override
protected void onHandleIntent(Intent intent) {
    // Check//  w  w  w  .  j av  a 2s .  c  o  m
    Log.d(TAG, "Checking for update for: " + intent.getStringExtra("update"));

    // Check for Internet connection
    final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
    if (activeNetwork == null || !activeNetwork.isConnected()) {
        Log.d(TAG, "No network connection");
        return;
    }

    boolean showNotification = false;
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    // Check a shard for updates
    if (intent.getStringExtra("API").equalsIgnoreCase("region")) {
        // Check region shards
        RegionData rData;
        if (intent.getStringExtra("region").equalsIgnoreCase("-1")) {
            if (intent.getStringExtra("shard").equalsIgnoreCase("messages")) {
                // Check for new messages
                try {
                    rData = API.getInstance(this).getRegionInfo(NationInfo.getInstance(this).getRegionId(),
                            RegionData.Shards.MESSAGES);
                } catch (RateLimitReachedException e) {
                    e.printStackTrace();
                    return;
                } catch (UnknownRegionException e) {
                    e.printStackTrace();
                    return;
                } catch (XmlPullParserException e) {
                    e.printStackTrace();
                    return;
                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                }

                if (rData.messages != null && rData.messages.size() > 0) {
                    RMBMessage msg = rData.messages.get(rData.messages.size() - 1);
                    long lastTS = prefs.getLong("update_region_messages_timestamp", -1);
                    String lastNation = prefs.getString("update_region_messages_nation", "");
                    if (lastTS != msg.timestamp && lastNation.compareToIgnoreCase(msg.message) != 0) {
                        // There are new messages
                        Log.d(TAG, "New messages!");
                        if (Region.shouldUpdate || NSDroid.shouldUpdate) { // Send broadcast to update RMB directly
                            Intent i = new Intent(NotificationsHelper.RMB_UPDATE_ACTION);
                            RMBMessageParcelable[] parcel = new RMBMessageParcelable[rData.messages.size()];
                            int t = 0;
                            for (RMBMessage m : rData.messages) {
                                parcel[t] = new RMBMessageParcelable(m);
                                t++;
                            }
                            i.putExtra("com.limewoodMedia.nsdroid.holders.RMBMessageParcelable", parcel);
                            sendBroadcast(i);

                            if (NSDroid.shouldUpdate) {
                                showNotification = true;
                            }
                        } else { // Not currently showing
                            showNotification = true;
                        }
                    } else {
                        // No new messages - set new alarm
                        NotificationsHelper.setAlarmForRMB(this,
                                Integer.parseInt(prefs.getString("rmb_update_interval", "-1")));
                    }
                }
            }
        }
    } else if (intent.getStringExtra("API").equalsIgnoreCase("issues")) {
        // Issues
        IssuesInfo issues = API.getInstance(this).getIssues();
        Log.d(TAG, "Issues: " + issues);
        if (issues != null) {
            if (issues.issues != null && issues.issues.size() > 0) {
                Log.d(TAG, "Issues: " + issues.issues.size());
                intent.putExtra("notification_number", issues.issues.size());
                showNotification = true;
            }
            if (issues.nextIssue != null) {
                Log.d(TAG, "Issues: " + issues.nextIssue);
                NotificationsHelper.setIssuesTimer(this, issues.nextIssue);
            }
        }
    }

    if (showNotification) {
        // Show notification icon
        Intent i;
        try {
            // Start activity with class name
            i = new Intent(this, Class.forName(intent.getStringExtra("class")));
            if (intent.hasExtra("page")) {
                i.putExtra("page", intent.getIntExtra("page", 0));
            }
            Log.d(TAG, "Build notification to update " + intent.getStringExtra("class"));
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            PendingIntent pi = PendingIntent.getActivity(this,
                    intent.getIntExtra("notification_id", NOTIFICATION_ID), i,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            NotificationCompat.Builder notifyBuilder = new NotificationCompat.Builder(this)
                    .setContentTitle(getResources()
                            .getString(intent.getIntExtra("notification_title", R.string.notification_title)))
                    .setContentText(getResources()
                            .getString(intent.getIntExtra("notification_text", R.string.notification_text)))
                    .setSmallIcon(R.drawable.app_icon).setAutoCancel(true).setContentIntent(pi)
                    .setOnlyAlertOnce(false).setWhen(System.currentTimeMillis());
            if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("notify_sound", true)
                    && intent.hasExtra("notification_sound")) {
                notifyBuilder.setSound(Uri.parse("android.resource://" + getPackageName() + "/"
                        + intent.getIntExtra("notification_sound", -1)));
            }
            if (intent.hasExtra("notification_number")) {
                notifyBuilder.setNumber(intent.getIntExtra("notification_number", 0)).setShowWhen(false);
            }
            Log.d(TAG, "Show notification");
            notificationManager.notify(intent.getIntExtra("notification_id", NOTIFICATION_ID),
                    notifyBuilder.getNotification());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

From source file:github.daneren2005.dsub.service.RESTMusicService.java

public int processOfflineScrobbles(final Context context, final ProgressListener progressListener)
        throws Exception {
    SharedPreferences offline = Util.getOfflineSync(context);
    SharedPreferences.Editor offlineEditor = offline.edit();
    int count = offline.getInt(Constants.OFFLINE_SCROBBLE_COUNT, 0);
    int retry = 0;
    for (int i = 1; i <= count; i++) {
        String id = offline.getString(Constants.OFFLINE_SCROBBLE_ID + i, null);
        long time = offline.getLong(Constants.OFFLINE_SCROBBLE_TIME + i, 0);
        if (id != null) {
            scrobble(id, true, time, context, progressListener);
        } else {//from  w ww. ja va 2s . co  m
            String search = offline.getString(Constants.OFFLINE_SCROBBLE_SEARCH + i, "");
            try {
                SearchCritera critera = new SearchCritera(search, 0, 0, 1);
                SearchResult result = searchNew(critera, context, progressListener);
                if (result.getSongs().size() == 1) {
                    Log.i(TAG,
                            "Query '" + search + "' returned song " + result.getSongs().get(0).getTitle()
                                    + " by " + result.getSongs().get(0).getArtist() + " with id "
                                    + result.getSongs().get(0).getId());
                    Log.i(TAG, "Scrobbling " + result.getSongs().get(0).getId() + " with time " + time);
                    scrobble(result.getSongs().get(0).getId(), true, time, context, progressListener);
                } else {
                    throw new Exception("Song not found on server");
                }
            } catch (Exception e) {
                Log.e(TAG, e.toString());
                retry++;
            }
        }
    }

    offlineEditor.putInt(Constants.OFFLINE_SCROBBLE_COUNT, 0);
    offlineEditor.commit();

    return count - retry;
}

From source file:jp.mixi.android.sdk.MixiContainerImpl.java

/**
 * ?/* w  w  w. ja v  a  2 s.  c o  m*/
 * 
 * @param contextWrapper ?activity
 * @param listener ???????????????(?????????)
 * @return ???????true
 * @throws RemoteException
 */
boolean restoreSession(final ContextWrapper contextWrapper) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            SharedPreferences prefs = contextWrapper.getSharedPreferences(MIXI_SESSION_KEY,
                    Context.MODE_PRIVATE);
            String appId = prefs.getString(CLIENT_ID, null);
            if (appId == null) {
                return;
            }
            setAccessToken(prefs.getString(ACCESS_TOKEN, null));
            setRefreshToken(prefs.getString(REFRESH_TOKEN, null));
            setAccessExpiresIn(prefs.getLong(EXPIRES, 0));
            if (isAuthorized()) {
                runAppCounter();
            }
        }
    }).start();
    if (getAccessToken() == null) {
        return false;
    }
    return true;
}

From source file:net.kidlogger.kidlogger.KLService.java

private long getLongPref(String key) {
    SharedPreferences pref = this.getSharedPreferences(PREF_NAME, 0);
    long value = pref.getLong(key, 0);
    return value;
}

From source file:com.ferdi2005.secondgram.voip.VoIPService.java

@Override
public void onCreate() {
    super.onCreate();
    FileLog.d("=============== VoIPService STARTING ===============");
    AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1
            && am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER) != null) {
        int outFramesPerBuffer = Integer
                .parseInt(am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER));
        VoIPController.setNativeBufferSize(outFramesPerBuffer);
    } else {//from  w  ww  .jav  a2 s . com
        VoIPController.setNativeBufferSize(
                AudioTrack.getMinBufferSize(48000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT)
                        / 2);
    }
    final SharedPreferences preferences = getSharedPreferences("mainconfig", MODE_PRIVATE);
    VoIPServerConfig.setConfig(preferences.getString("voip_server_config", "{}"));
    if (System.currentTimeMillis() - preferences.getLong("voip_server_config_updated", 0) > 24 * 3600000) {
        ConnectionsManager.getInstance().sendRequest(new TLRPC.TL_phone_getCallConfig(), new RequestDelegate() {
            @Override
            public void run(TLObject response, TLRPC.TL_error error) {
                if (error == null) {
                    String data = ((TLRPC.TL_dataJSON) response).data;
                    VoIPServerConfig.setConfig(data);
                    preferences.edit().putString("voip_server_config", data)
                            .putLong("voip_server_config_updated",
                                    BuildConfig.DEBUG ? 0 : System.currentTimeMillis())
                            .apply();
                }
            }
        });
    }
    try {
        controller = new VoIPController();
        controller.setConnectionStateListener(this);
        controller.setConfig(MessagesController.getInstance().callPacketTimeout / 1000.0,
                MessagesController.getInstance().callConnectTimeout / 1000.0,
                preferences.getInt("VoipDataSaving", VoIPController.DATA_SAVING_NEVER));

        cpuWakelock = ((PowerManager) getSystemService(POWER_SERVICE))
                .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "telegram-voip");
        cpuWakelock.acquire();

        btAdapter = am.isBluetoothScoAvailableOffCall() ? BluetoothAdapter.getDefaultAdapter() : null;

        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(ACTION_HEADSET_PLUG);
        if (btAdapter != null) {
            filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
            filter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
        }
        filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
        filter.addAction(getPackageName() + ".END_CALL");
        filter.addAction(getPackageName() + ".DECLINE_CALL");
        filter.addAction(getPackageName() + ".ANSWER_CALL");
        registerReceiver(receiver, filter);

        ConnectionsManager.getInstance().setAppPaused(false, false);

        soundPool = new SoundPool(1, AudioManager.STREAM_VOICE_CALL, 0);
        spConnectingId = soundPool.load(this, R.raw.voip_connecting, 1);
        spRingbackID = soundPool.load(this, R.raw.voip_ringback, 1);
        spFailedID = soundPool.load(this, R.raw.voip_failed, 1);
        spEndId = soundPool.load(this, R.raw.voip_end, 1);
        spBusyId = soundPool.load(this, R.raw.voip_busy, 1);

        am.registerMediaButtonEventReceiver(new ComponentName(this, VoIPMediaButtonReceiver.class));

        if (btAdapter != null && btAdapter.isEnabled()) {
            int headsetState = btAdapter.getProfileConnectionState(BluetoothProfile.HEADSET);
            updateBluetoothHeadsetState(headsetState == BluetoothProfile.STATE_CONNECTED);
            if (headsetState == BluetoothProfile.STATE_CONNECTED)
                am.setBluetoothScoOn(true);
            for (StateListener l : stateListeners)
                l.onAudioSettingsChanged();
        }

        NotificationCenter.getInstance().addObserver(this, NotificationCenter.appDidLogout);
    } catch (Exception x) {
        FileLog.e("error initializing voip controller", x);
        callFailed();
    }
}