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.zsxj.pda.ui.client.LoginActivity.java

private boolean downloading() {
    DownloadManager.Query query = new DownloadManager.Query();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    long downloadId = prefs.getLong(PrefKeys.DOWNLOAD_ID, 0);
    query.setFilterById(downloadId);//from ww w  . ja va  2  s . c o m
    DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    Cursor c = dm.query(query);
    if (c.moveToNext()) {
        int statusIdx = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
        int status = c.getInt(statusIdx);
        if (DownloadManager.STATUS_RUNNING == status) {
            return true;
        }
    }
    return false;
}

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

/**
 * Cordova interface to perform a login/*from   w  ww .  j  av  a 2  s. co m*/
 *
 * @param args
 * @param callbackId
 * @return PluginResult
 * @throws JSONException
 * @throws MalformedURLException
 * @throws IOException
 */
public PluginResult login(final JSONArray args, final CallbackContext callbackId)
        throws JSONException, MalformedURLException, IOException {
    Log.d(CLASS, "login() :" + args.toString());
    JSONObject params = args.getJSONObject(0);
    PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);

    if (params.has("appId"))
        this.appId = params.getString("appId");
    Facebook facebook = this.getFacebook();

    // 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);

    if (!this.getFacebook().isSessionValid()) {
        JSONArray permissionsArray = (JSONArray) params.get("permissions");
        final String[] permissions = new String[permissionsArray.length()];
        for (int i = 0; i < permissionsArray.length(); i++) {
            permissions[i] = permissionsArray.getString(i);
        }

        final FacebookConnect me = this;
        this.authorizeDialogListener = new AuthorizeDialogListener(me, callbackId);
        this.cordova.setActivityResultCallback(this);
        Runnable runnable = new Runnable() {
            public void run() {
                me.getFacebook().authorize(me.cordova.getActivity(), permissions, me.authorizeDialogListener);
            };
        };
        pluginResult.setKeepCallback(true);
        this.cordova.getActivity().runOnUiThread(runnable);
    } else {
        JSONObject result = new JSONObject(facebook.request("/me"));
        result.put("accessToken", accessToken);
        result.put("expirationDate", accessExpires);
        Log.d(CLASS, "login::result " + result.toString());
        pluginResult = new PluginResult(PluginResult.Status.OK, result);
    }

    return pluginResult;
}

From source file:com.example.jumpnote.android.SyncAdapter.java

@Override
public void onPerformSync(final Account account, Bundle extras, String authority,
        final ContentProviderClient provider, final SyncResult syncResult) {
    TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
    String clientDeviceId = tm.getDeviceId();

    final long newSyncTime = System.currentTimeMillis();

    final boolean uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false);
    final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
    final boolean initialize = extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false);

    C2DMReceiver.refreshAppC2DMRegistrationState(mContext);

    Log.i(TAG, "Beginning " + (uploadOnly ? "upload-only" : "full") + " sync for account " + account.name);

    // Read this account's sync metadata
    final SharedPreferences syncMeta = mContext.getSharedPreferences("sync:" + account.name, 0);
    long lastSyncTime = syncMeta.getLong(LAST_SYNC, 0);
    long lastServerSyncTime = syncMeta.getLong(SERVER_LAST_SYNC, 0);

    // Check for changes in either app-wide auto sync registration information, or changes in
    // the user's preferences for auto sync on this account; if either changes, piggy back the
    // new registration information in this sync.
    long lastRegistrationChangeTime = C2DMessaging.getLastRegistrationChange(mContext);

    boolean autoSyncDesired = ContentResolver.getMasterSyncAutomatically()
            && ContentResolver.getSyncAutomatically(account, JumpNoteContract.AUTHORITY);
    boolean autoSyncEnabled = syncMeta.getBoolean(DM_REGISTERED, false);

    // Will be 0 for no change, -1 for unregister, 1 for register.
    final int deviceRegChange;
    JsonRpcClient.Call deviceRegCall = null;
    if (autoSyncDesired != autoSyncEnabled || lastRegistrationChangeTime > lastSyncTime || initialize
            || manualSync) {// w w w  .  j  ava2s  .  com

        String registrationId = C2DMessaging.getRegistrationId(mContext);
        deviceRegChange = (autoSyncDesired && registrationId != null) ? 1 : -1;

        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG,
                    "Auto sync selection or registration information has changed, "
                            + (deviceRegChange == 1 ? "registering" : "unregistering")
                            + " messaging for this device, for account " + account.name);
        }

        try {
            if (deviceRegChange == 1) {
                // Register device for auto sync on this account.
                deviceRegCall = new JsonRpcClient.Call(JumpNoteProtocol.DevicesRegister.METHOD);
                JSONObject params = new JSONObject();

                DeviceRegistration device = new DeviceRegistration(clientDeviceId, DEVICE_TYPE, registrationId);
                params.put(JumpNoteProtocol.DevicesRegister.ARG_DEVICE, device.toJSON());
                deviceRegCall.setParams(params);
            } else {
                // Unregister device for auto sync on this account.
                deviceRegCall = new JsonRpcClient.Call(JumpNoteProtocol.DevicesUnregister.METHOD);
                JSONObject params = new JSONObject();
                params.put(JumpNoteProtocol.DevicesUnregister.ARG_DEVICE_ID, clientDeviceId);
                deviceRegCall.setParams(params);
            }
        } catch (JSONException e) {
            logErrorMessage("Error generating device registration remote RPC parameters.", manualSync);
            e.printStackTrace();
            return;
        }
    } else {
        deviceRegChange = 0;
    }

    // Get the list of locally changed notes. If this is an upload-only sync and there were
    // no local changes, cancel the sync.
    List<ModelJava.Note> locallyChangedNotes = null;
    try {
        locallyChangedNotes = getLocallyChangedNotes(provider, account, new Date(lastSyncTime));
    } catch (RemoteException e) {
        logErrorMessage("Remote exception accessing content provider: " + e.getMessage(), manualSync);
        e.printStackTrace();
        syncResult.stats.numIoExceptions++;
        return;
    }

    if (uploadOnly && locallyChangedNotes.isEmpty() && deviceRegCall == null) {
        Log.i(TAG, "No local changes; upload-only sync canceled.");
        return;
    }

    // Set up the RPC sync calls
    final AuthenticatedJsonRpcJavaClient jsonRpcClient = new AuthenticatedJsonRpcJavaClient(mContext,
            Config.SERVER_AUTH_URL_TEMPLATE, Config.SERVER_RPC_URL);
    try {
        jsonRpcClient.blockingAuthenticateAccount(account,
                manualSync ? AuthenticatedJsonRpcJavaClient.NEED_AUTH_INTENT
                        : AuthenticatedJsonRpcJavaClient.NEED_AUTH_NOTIFICATION,
                false);
    } catch (AuthenticationException e) {
        logErrorMessage("Authentication exception when attempting to sync.", manualSync);
        e.printStackTrace();
        syncResult.stats.numAuthExceptions++;
        return;
    } catch (OperationCanceledException e) {
        Log.i(TAG, "Sync for account " + account.name + " manually canceled.");
        return;
    } catch (RequestedUserAuthenticationException e) {
        syncResult.stats.numAuthExceptions++;
        return;
    } catch (InvalidAuthTokenException e) {
        logErrorMessage("Invalid auth token provided by AccountManager when attempting to " + "sync.",
                manualSync);
        e.printStackTrace();
        syncResult.stats.numAuthExceptions++;
        return;
    }

    // Set up the notes sync call.
    JsonRpcClient.Call notesSyncCall = new JsonRpcClient.Call(JumpNoteProtocol.NotesSync.METHOD);
    try {
        JSONObject params = new JSONObject();
        params.put(JumpNoteProtocol.ARG_CLIENT_DEVICE_ID, clientDeviceId);
        params.put(JumpNoteProtocol.NotesSync.ARG_SINCE_DATE,
                Util.formatDateISO8601(new Date(lastServerSyncTime)));

        JSONArray locallyChangedNotesJson = new JSONArray();
        for (ModelJava.Note locallyChangedNote : locallyChangedNotes) {
            locallyChangedNotesJson.put(locallyChangedNote.toJSON());
        }

        params.put(JumpNoteProtocol.NotesSync.ARG_LOCAL_NOTES, locallyChangedNotesJson);
        notesSyncCall.setParams(params);
    } catch (JSONException e) {
        logErrorMessage("Error generating sync remote RPC parameters.", manualSync);
        e.printStackTrace();
        syncResult.stats.numParseExceptions++;
        return;
    }

    List<JsonRpcClient.Call> jsonRpcCalls = new ArrayList<JsonRpcClient.Call>();
    jsonRpcCalls.add(notesSyncCall);
    if (deviceRegChange != 0)
        jsonRpcCalls.add(deviceRegCall);

    jsonRpcClient.callBatch(jsonRpcCalls, new JsonRpcClient.BatchCallback() {
        public void onData(Object[] data) {
            if (data[0] != null) {
                // Read notes sync data.
                JSONObject dataJson = (JSONObject) data[0];
                try {
                    List<ModelJava.Note> changedNotes = new ArrayList<ModelJava.Note>();
                    JSONArray notesJson = dataJson.getJSONArray(JumpNoteProtocol.NotesSync.RET_NOTES);
                    for (int i = 0; i < notesJson.length(); i++) {
                        changedNotes.add(new ModelJava.Note(notesJson.getJSONObject(i)));
                    }

                    reconcileSyncedNotes(provider, account, changedNotes, syncResult.stats);

                    // If sync is successful (no exceptions thrown), update sync metadata
                    long newServerSyncTime = Util
                            .parseDateISO8601(dataJson.getString(JumpNoteProtocol.NotesSync.RET_NEW_SINCE_DATE))
                            .getTime();
                    syncMeta.edit().putLong(LAST_SYNC, newSyncTime).commit();
                    syncMeta.edit().putLong(SERVER_LAST_SYNC, newServerSyncTime).commit();
                    Log.i(TAG, "Sync complete, setting last sync time to " + Long.toString(newSyncTime));
                } catch (JSONException e) {
                    logErrorMessage("Error parsing note sync RPC response", manualSync);
                    e.printStackTrace();
                    syncResult.stats.numParseExceptions++;
                    return;
                } catch (ParseException e) {
                    logErrorMessage("Error parsing note sync RPC response", manualSync);
                    e.printStackTrace();
                    syncResult.stats.numParseExceptions++;
                    return;
                } catch (RemoteException e) {
                    logErrorMessage("RemoteException in reconcileSyncedNotes: " + e.getMessage(), manualSync);
                    e.printStackTrace();
                    return;
                } catch (OperationApplicationException e) {
                    logErrorMessage("Could not apply batch operations to content provider: " + e.getMessage(),
                            manualSync);
                    e.printStackTrace();
                    return;
                } finally {
                    provider.release();
                }
            }

            // Read device reg data.
            if (deviceRegChange != 0) {
                // data[1] will be null in case of an error (successful unregisters
                // will have an empty JSONObject, not null).
                boolean registered = (data[1] != null && deviceRegChange == 1);
                syncMeta.edit().putBoolean(DM_REGISTERED, registered).commit();
                if (Log.isLoggable(TAG, Log.DEBUG)) {
                    Log.d(TAG, "Stored account auto sync registration state: " + Boolean.toString(registered));
                }
            }
        }

        public void onError(int callIndex, JsonRpcException e) {
            if (e.getHttpCode() == 403) {
                Log.w(TAG, "Got a 403 response, invalidating App Engine ACSID token");
                jsonRpcClient.invalidateAccountAcsidToken(account);
            }

            provider.release();
            logErrorMessage("Error calling remote note sync RPC", manualSync);
            e.printStackTrace();
        }
    });
}

From source file:com.adkdevelopment.earthquakesurvival.data.syncadapter.SyncAdapter.java

/**
 * Raises a notification with a biggest earthquake with each sync
 *
 * @param notifyValues data with the biggest recent earthquake
 *//*from   w  ww. j  a  v a  2 s  .  co m*/
private void sendNotification(ContentValues notifyValues) {

    Context context = getContext();

    if (Utilities.getNotificationsPrefs(context) && !Utilities.checkForeground(context)) {

        //checking the last update and notify if it' the first of the day
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        String lastNotificationKey = context.getString(R.string.sharedprefs_key_lastnotification);
        long lastSync = prefs.getLong(lastNotificationKey, 0);

        if (System.currentTimeMillis() - lastSync >= DateUtils.DAY_IN_MILLIS) {
            Intent intent = new Intent(context, DetailActivity.class);

            double latitude = notifyValues.getAsDouble(EarthquakeColumns.LATITUDE);
            double longitude = notifyValues.getAsDouble(EarthquakeColumns.LONGITUDE);
            LatLng latLng = new LatLng(latitude, longitude);

            String distance = context.getString(R.string.earthquake_distance,
                    LocationUtils.getDistance(latLng, LocationUtils.getLocation(context)));

            String magnitude = context.getString(R.string.earthquake_magnitude,
                    notifyValues.getAsDouble(EarthquakeColumns.MAG));
            String date = Utilities.getRelativeDate(notifyValues.getAsLong(EarthquakeColumns.TIME));

            double depth = notifyValues.getAsDouble(EarthquakeColumns.DEPTH);

            intent.putExtra(Feature.MAGNITUDE, notifyValues.getAsDouble(EarthquakeColumns.MAG));
            intent.putExtra(Feature.PLACE, notifyValues.getAsString(EarthquakeColumns.PLACE));
            intent.putExtra(Feature.DATE, date);
            intent.putExtra(Feature.LINK, notifyValues.getAsString(EarthquakeColumns.URL));
            intent.putExtra(Feature.LATLNG, latLng);
            intent.putExtra(Feature.DISTANCE, distance);
            intent.putExtra(Feature.DEPTH, depth);
            intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

            PendingIntent pendingIntent = PendingIntent.getActivity(context, EarthquakeObject.NOTIFICATION_ID_1,
                    intent, PendingIntent.FLAG_UPDATE_CURRENT);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

            Bitmap largeIcon = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);

            builder.setDefaults(Notification.DEFAULT_ALL).setAutoCancel(true)
                    .setContentTitle(context.getString(R.string.earthquake_statistics_largest))
                    .setContentText(context.getString(R.string.earthquake_magnitude,
                            notifyValues.get(EarthquakeColumns.MAG)))
                    .setContentIntent(pendingIntent).setSmallIcon(R.drawable.ic_info_black_24dp)
                    .setLargeIcon(largeIcon).setTicker(context.getString(R.string.app_name))
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .bigText(notifyValues.get(EarthquakeColumns.PLACE).toString() + "\n" + magnitude
                                    + "\n" + context.getString(R.string.earthquake_depth, depth) + "\n"
                                    + distance + "\n" + date))
                    .setGroup(EarthquakeObject.NOTIFICATION_GROUP).setGroupSummary(true);

            NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context);
            managerCompat.notify(EarthquakeObject.NOTIFICATION_ID_1, builder.build());

            //refreshing last sync
            boolean success = prefs.edit().putLong(lastNotificationKey, System.currentTimeMillis()).commit();
        }
    }
}

From source file:com.samsung.android.remindme.SyncAdapter.java

@Override
public void onPerformSync(final Account account, Bundle extras, String authority,
        final ContentProviderClient provider, final SyncResult syncResult) {
    Log.i(TAG, "onPerformSync called!");
    TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
    String clientDeviceId = tm.getDeviceId();

    final long newSyncTime = System.currentTimeMillis();

    final boolean uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false);
    final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
    final boolean initialize = extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false);

    C2DMReceiver.refreshAppC2DMRegistrationState(mContext);

    Log.i(TAG, "Beginning " + (uploadOnly ? "upload-only" : "full") + " sync for account " + account.name);

    // Read this account's sync metadata
    final SharedPreferences syncMeta = mContext.getSharedPreferences("sync:" + account.name, 0);
    long lastSyncTime = syncMeta.getLong(LAST_SYNC, 0);
    long lastServerSyncTime = syncMeta.getLong(SERVER_LAST_SYNC, 0);

    // Check for changes in either app-wide auto sync registration information, or changes in
    // the user's preferences for auto sync on this account; if either changes, piggy back the
    // new registration information in this sync.
    long lastRegistrationChangeTime = C2DMessaging.getLastRegistrationChange(mContext);

    boolean autoSyncDesired = ContentResolver.getMasterSyncAutomatically()
            && ContentResolver.getSyncAutomatically(account, RemindMeContract.AUTHORITY);
    boolean autoSyncEnabled = syncMeta.getBoolean(DM_REGISTERED, false);

    // Will be 0 for no change, -1 for unregister, 1 for register.
    final int deviceRegChange;
    JsonRpcClient.Call deviceRegCall = null;
    if (autoSyncDesired != autoSyncEnabled || lastRegistrationChangeTime > lastSyncTime || initialize
            || manualSync) {/*w w w .  ja  v a 2  s .  c om*/

        String registrationId = C2DMessaging.getRegistrationId(mContext);
        deviceRegChange = (autoSyncDesired && registrationId != null) ? 1 : -1;

        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG,
                    "Auto sync selection or registration information has changed, "
                            + (deviceRegChange == 1 ? "registering" : "unregistering")
                            + " messaging for this device, for account " + account.name);
        }

        try {
            if (deviceRegChange == 1) {
                // Register device for auto sync on this account.
                deviceRegCall = new JsonRpcClient.Call(RemindMeProtocol.DevicesRegister.METHOD);
                JSONObject params = new JSONObject();

                DeviceRegistration device = new DeviceRegistration(clientDeviceId, DEVICE_TYPE, registrationId);
                params.put(RemindMeProtocol.DevicesRegister.ARG_DEVICE, device.toJSON());
                deviceRegCall.setParams(params);
            } else {
                // Unregister device for auto sync on this account.
                deviceRegCall = new JsonRpcClient.Call(RemindMeProtocol.DevicesUnregister.METHOD);
                JSONObject params = new JSONObject();
                params.put(RemindMeProtocol.DevicesUnregister.ARG_DEVICE_ID, clientDeviceId);
                deviceRegCall.setParams(params);
            }
        } catch (JSONException e) {
            logErrorMessage("Error generating device registration remote RPC parameters.", manualSync);
            e.printStackTrace();
            return;
        }
    } else {
        deviceRegChange = 0;
    }

    // Get the list of locally changed alerts. If this is an upload-only sync and there were
    // no local changes, cancel the sync.
    List<ModelJava.Alert> locallyChangedAlerts = null;
    try {
        locallyChangedAlerts = getLocallyChangedAlerts(provider, account, new Date(lastSyncTime));
    } catch (RemoteException e) {
        logErrorMessage("Remote exception accessing content provider: " + e.getMessage(), manualSync);
        e.printStackTrace();
        syncResult.stats.numIoExceptions++;
        return;
    }

    if (uploadOnly && locallyChangedAlerts.isEmpty() && deviceRegCall == null) {
        Log.i(TAG, "No local changes; upload-only sync canceled.");
        return;
    }

    // Set up the RPC sync calls
    final AuthenticatedJsonRpcJavaClient jsonRpcClient = new AuthenticatedJsonRpcJavaClient(mContext,
            Config.SERVER_AUTH_URL_TEMPLATE, Config.SERVER_RPC_URL);
    try {
        jsonRpcClient.blockingAuthenticateAccount(account,
                manualSync ? AuthenticatedJsonRpcJavaClient.NEED_AUTH_INTENT
                        : AuthenticatedJsonRpcJavaClient.NEED_AUTH_NOTIFICATION,
                false);
    } catch (AuthenticationException e) {
        logErrorMessage("Authentication exception when attempting to sync. root cause: " + e.getMessage(),
                manualSync);
        e.printStackTrace();

        syncResult.stats.numAuthExceptions++;
        return;
    } catch (OperationCanceledException e) {
        Log.i(TAG, "Sync for account " + account.name + " manually canceled.");
        return;
    } catch (RequestedUserAuthenticationException e) {
        syncResult.stats.numAuthExceptions++;
        return;
    } catch (InvalidAuthTokenException e) {
        logErrorMessage("Invalid auth token provided by AccountManager when attempting to " + "sync.",
                manualSync);
        e.printStackTrace();
        syncResult.stats.numAuthExceptions++;
        return;
    }

    // Set up the alerts sync call.
    JsonRpcClient.Call alertsSyncCall = new JsonRpcClient.Call(RemindMeProtocol.AlertsSync.METHOD);
    try {
        JSONObject params = new JSONObject();
        params.put(RemindMeProtocol.ARG_CLIENT_DEVICE_ID, clientDeviceId);
        params.put(RemindMeProtocol.AlertsSync.ARG_SINCE_DATE,
                Util.formatDateISO8601(new Date(lastServerSyncTime)));

        JSONArray locallyChangedAlertsJson = new JSONArray();
        for (ModelJava.Alert locallyChangedAlert : locallyChangedAlerts) {
            locallyChangedAlertsJson.put(locallyChangedAlert.toJSON());
        }

        params.put(RemindMeProtocol.AlertsSync.ARG_LOCAL_NOTES, locallyChangedAlertsJson);
        alertsSyncCall.setParams(params);
    } catch (JSONException e) {
        logErrorMessage("Error generating sync remote RPC parameters.", manualSync);
        e.printStackTrace();
        syncResult.stats.numParseExceptions++;
        return;
    }

    List<JsonRpcClient.Call> jsonRpcCalls = new ArrayList<JsonRpcClient.Call>();
    jsonRpcCalls.add(alertsSyncCall);
    if (deviceRegChange != 0)
        jsonRpcCalls.add(deviceRegCall);

    jsonRpcClient.callBatch(jsonRpcCalls, new JsonRpcClient.BatchCallback() {
        public void onData(Object[] data) {
            if (data[0] != null) {
                // Read alerts sync data.
                JSONObject dataJson = (JSONObject) data[0];
                try {
                    List<ModelJava.Alert> changedAlerts = new ArrayList<ModelJava.Alert>();
                    JSONArray alertsJson = dataJson.getJSONArray(RemindMeProtocol.AlertsSync.RET_NOTES);
                    for (int i = 0; i < alertsJson.length(); i++) {
                        changedAlerts.add(new ModelJava.Alert(alertsJson.getJSONObject(i)));
                    }

                    reconcileSyncedAlerts(provider, account, changedAlerts, syncResult.stats);

                    // If sync is successful (no exceptions thrown), update sync metadata
                    long newServerSyncTime = Util
                            .parseDateISO8601(
                                    dataJson.getString(RemindMeProtocol.AlertsSync.RET_NEW_SINCE_DATE))
                            .getTime();
                    syncMeta.edit().putLong(LAST_SYNC, newSyncTime).commit();
                    syncMeta.edit().putLong(SERVER_LAST_SYNC, newServerSyncTime).commit();
                    Log.i(TAG, "Sync complete, setting last sync time to " + Long.toString(newSyncTime));
                } catch (JSONException e) {
                    logErrorMessage("Error parsing alert sync RPC response", manualSync);
                    e.printStackTrace();
                    syncResult.stats.numParseExceptions++;
                    return;
                } catch (ParseException e) {
                    logErrorMessage("Error parsing alert sync RPC response", manualSync);
                    e.printStackTrace();
                    syncResult.stats.numParseExceptions++;
                    return;
                } catch (RemoteException e) {
                    logErrorMessage("RemoteException in reconcileSyncedAlerts: " + e.getMessage(), manualSync);
                    e.printStackTrace();
                    return;
                } catch (OperationApplicationException e) {
                    logErrorMessage("Could not apply batch operations to content provider: " + e.getMessage(),
                            manualSync);
                    e.printStackTrace();
                    return;
                } finally {
                    provider.release();
                }
            }

            // Read device reg data.
            if (deviceRegChange != 0) {
                // data[1] will be null in case of an error (successful unregisters
                // will have an empty JSONObject, not null).
                boolean registered = (data[1] != null && deviceRegChange == 1);
                syncMeta.edit().putBoolean(DM_REGISTERED, registered).commit();
                if (Log.isLoggable(TAG, Log.DEBUG)) {
                    Log.d(TAG, "Stored account auto sync registration state: " + Boolean.toString(registered));
                }
            }
        }

        public void onError(int callIndex, JsonRpcException e) {
            if (e.getHttpCode() == 403) {
                Log.w(TAG, "Got a 403 response, invalidating App Engine ACSID token");
                jsonRpcClient.invalidateAccountAcsidToken(account);
            }

            provider.release();
            logErrorMessage("Error calling remote alert sync RPC", manualSync);
            e.printStackTrace();
        }
    });
}

From source file:mx.com.adolfogarcia.popularmovies.data.RestfulServiceConfiguration.java

/**
 * Returns the epoch time at which the configuration was last updated or
 * zero if it has never been set. Note that this only applies to the
 * properties (those that appear in {@link ImageConfigurationJsonModel}),
 * if other attributes (e.g. the last movie page retrieved) are changed,
 * the time is not updated.//from  w ww  .  java  2s . c  o m
 *
 * @return the epoch time at which the configuration was last updated or
 *     zero if it has never been set.
 */
public long getLastUpdateTime() {
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mWeakContext.get());
    return settings.getLong(PREFERENCES_KEY_LAST_UPDATE, 0);
}

From source file:com.jdom.get.stuff.done.android.AndroidSyncStrategy.java

private String getToken() {
    long start = System.currentTimeMillis();
    SharedPreferences prefs = activity.getSharedPreferences(Constants.AUTH_TOKEN_TYPE, Activity.MODE_PRIVATE);
    String token = prefs.getString(Constants.AUTH_TOKEN_TYPE, null);
    long lastTokenRetrievalTime = prefs.getLong(Constants.TOKEN_RETRIEVAL_TIME, 0);

    long timeSinceRetrievedLastToken = System.currentTimeMillis() - lastTokenRetrievalTime;
    long timeStillValid = Constants.TOKEN_VALID_DURATION - timeSinceRetrievedLastToken;
    if (token == null || timeStillValid < 1) {
        long portionStart = System.currentTimeMillis();
        Log.d(CLASS_NAME, "Token is no longer valid.");
        GoogleAccountManager accountManager = new GoogleAccountManager(activity);
        Account account = getAccount();//from   w ww  .j  a  va2  s.  c o  m

        accountManager.manager.invalidateAuthToken(account.type, token);
        AccountManagerFuture<Bundle> future = accountManager.manager.getAuthToken(account,
                Constants.AUTH_TOKEN_TYPE, null, activity, null, null);
        try {
            Bundle result = future.getResult();
            token = result.getString(AccountManager.KEY_AUTHTOKEN);

            Editor editor = prefs.edit();
            editor.putString(Constants.AUTH_TOKEN_TYPE, token);
            editor.putLong(Constants.TOKEN_RETRIEVAL_TIME, System.currentTimeMillis());
            editor.commit();

        } catch (Exception e) {
            handleException(e);
        }
        AndroidSyncStrategy.logTimeTaken("Retrieving new token", portionStart);
    } else {
        Log.d(CLASS_NAME, "Token is still valid for [" + timeStillValid + "] ms.");
    }

    AndroidSyncStrategy.logTimeTaken("Retrieving token", start);
    return token;
}

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

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

    // Before we do anything else, check for a saved draft; if one exists, load it
    SharedPreferences prefMain = getActivity().getPreferences(Context.MODE_PRIVATE);
    if (getId() == R.id.noteViewEdit && prefMain.getLong("draft-name", 0) != 0) {
        Bundle bundle = new Bundle();
        bundle.putString("filename", "draft");

        Fragment fragment = new NoteEditFragment();
        fragment.setArguments(bundle);// w  w w .ja  v  a2s. c o  m

        // Add NoteEditFragment
        getFragmentManager().beginTransaction().replace(R.id.noteViewEdit, fragment, "NoteEditFragment")
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).commit();
    } else {
        if (getId() == R.id.noteViewEdit) {
            // Change window title
            String title = getResources().getString(R.string.app_name);

            getActivity().setTitle(title);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Bitmap bitmap = ((BitmapDrawable) ContextCompat.getDrawable(getActivity(),
                        R.drawable.ic_recents_logo)).getBitmap();

                ActivityManager.TaskDescription taskDescription = new ActivityManager.TaskDescription(title,
                        bitmap, ContextCompat.getColor(getActivity(), R.color.primary));
                getActivity().setTaskDescription(taskDescription);
            }

            // Don't show the Up button in the action bar, and disable the button
            ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false);
            ((AppCompatActivity) getActivity()).getSupportActionBar().setHomeButtonEnabled(false);
        }

        // Read preferences
        SharedPreferences pref = getActivity()
                .getSharedPreferences(getActivity().getPackageName() + "_preferences", Context.MODE_PRIVATE);
        theme = pref.getString("theme", "light-sans");
        sortBy = pref.getString("sort_by", "date");
        showDate = pref.getBoolean("show_date", false);
        directEdit = pref.getBoolean("direct_edit", false);

        // Apply theme
        LinearLayout noteViewEdit = getActivity().findViewById(R.id.noteViewEdit);
        LinearLayout noteList = getActivity().findViewById(R.id.noteList);

        if (theme.contains("light")) {
            noteViewEdit.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background));
            noteList.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background));
        }

        if (theme.contains("dark")) {
            noteViewEdit
                    .setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark));
            noteList.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark));
        }

        // Declare ListView
        listView = getActivity().findViewById(R.id.listView1);

        // Refresh list of notes onResume (instead of onCreate) to reflect additions/deletions and preference changes
        listNotes();
    }
}

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

private void deleteAccount() {

    //Remove all Sync
    if (acc == null) {
        return;/*from   w  w  w.j ava  2 s .com*/
    }
    OperationsRequestGroup group = new OperationsRequestGroup(getActivity(), acc);
    group.enqueue(new CleanSyncFavoriteRequest(acc, true)
            .setNotificationVisibility(OperationRequest.VISIBILITY_HIDDEN));
    BatchOperationManager.getInstance(getActivity()).enqueue(group);

    //Delete Account
    getActivity().getContentResolver().delete(AccountManager.getUri(acc.getId()), null, null);

    LocalBroadcastManager.getInstance(getActivity())
            .sendBroadcast(new Intent(IntentIntegrator.ACTION_DELETE_ACCOUNT_COMPLETED));

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

    if (SessionUtils.getAccount(getActivity()) != null
            && SessionUtils.getAccount(getActivity()).getId() == acc.getId()) {
        ((BaseActivity) getActivity()).setCurrentAccount(null);
        SharedPreferences settings = getActivity().getSharedPreferences(AccountsPreferences.ACCOUNT_PREFS, 0);
        long id = settings.getLong(AccountsPreferences.ACCOUNT_DEFAULT, -1);
        if (id == acc.getId()) {
            settings.edit().putLong(AccountsPreferences.ACCOUNT_DEFAULT, -1).commit();
        }
        ((BaseActivity) getActivity())
                .setCurrentAccount(AccountManager.getInstance(getActivity()).getDefaultAccount());
    }

    Cursor cursor = getActivity().getContentResolver().query(AccountManager.CONTENT_URI,
            AccountManager.COLUMN_ALL, null, null, null);
    if (cursor.getCount() > 0) {
        // Remove Details panel
        if (DisplayUtils.hasCentralPane(getActivity())) {
            FragmentDisplayer.removeFragment(getActivity(), AccountDetailsFragment.TAG);
        } else {
            getFragmentManager().popBackStack(AccountDetailsFragment.TAG,
                    FragmentManager.POP_BACK_STACK_INCLUSIVE);
        }
    } else {
        // If no account left, we remove all preferences
        // Remove preferences
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
        Editor editor = sharedPref.edit();
        editor.clear();
        editor.commit();

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

From source file:org.bwgz.quotation.activity.QuotationActivity.java

private long getRemaingAdFreePeriod() {
    SharedPreferences preferences = getSharedPreferences(QuotationApplication.APPLICATION_PREFERENCES,
            Context.MODE_PRIVATE);
    long date = preferences.getLong(QuotationApplication.PREFERENCE_APPLICATION_INITIALIZED_DATE, 0);

    return AD_FREE_PERIOD - ((date != 0) ? (System.currentTimeMillis() - date) : 0);
}