List of usage examples for android.content SharedPreferences getLong
long getLong(String key, long defValue);
From source file:com.trk.aboutme.facebook.Settings.java
/** * Manually publish install attribution to the Facebook graph. Internally handles caching repeat calls to prevent * multiple installs being published to the graph. * @param context the current Context//from w ww .jav a 2s.com * @param applicationId the fb application being published. * @return returns a Response object, carrying the server response, or an error. */ public static Response publishInstallAndWaitForResponse(final Context context, final String applicationId) { try { if (context == null || applicationId == null) { throw new IllegalArgumentException("Both context and applicationId must be non-null"); } String attributionId = Settings.getAttributionId(context.getContentResolver()); SharedPreferences preferences = context.getSharedPreferences(ATTRIBUTION_PREFERENCES, Context.MODE_PRIVATE); String pingKey = applicationId + "ping"; String jsonKey = applicationId + "json"; long lastPing = preferences.getLong(pingKey, 0); String lastResponseJSON = preferences.getString(jsonKey, null); GraphObject publishParams = GraphObject.Factory.create(); publishParams.setProperty(ANALYTICS_EVENT, MOBILE_INSTALL_EVENT); publishParams.setProperty(ATTRIBUTION_KEY, attributionId); String publishUrl = String.format(PUBLISH_ACTIVITY_PATH, applicationId); Request publishRequest = Request.newPostRequest(null, publishUrl, publishParams, null); if (lastPing != 0) { GraphObject graphObject = null; try { if (lastResponseJSON != null) { graphObject = GraphObject.Factory.create(new JSONObject(lastResponseJSON)); } } catch (JSONException je) { // return the default graph object if there is any problem reading the data. } if (graphObject == null) { return Response.createResponsesFromString("true", null, new RequestBatch(publishRequest), true) .get(0); } else { return new Response(null, null, graphObject, true); } } else if (attributionId == null) { throw new FacebookException("No attribution id returned from the Facebook application"); } else { if (!Utility.queryAppAttributionSupportAndWait(applicationId)) { throw new FacebookException("Install attribution has been disabled on the server."); } Response publishResponse = publishRequest.executeAndWait(); // denote success since no error threw from the post. SharedPreferences.Editor editor = preferences.edit(); lastPing = System.currentTimeMillis(); editor.putLong(pingKey, lastPing); // if we got an object response back, cache the string of the JSON. if (publishResponse.getGraphObject() != null && publishResponse.getGraphObject().getInnerJSONObject() != null) { editor.putString(jsonKey, publishResponse.getGraphObject().getInnerJSONObject().toString()); } editor.commit(); return publishResponse; } } catch (Exception e) { // if there was an error, fall through to the failure case. Utility.logd("Facebook-publish", e); return new Response(null, null, new FacebookRequestError(null, e)); } }
From source file:com.cmgapps.android.util.CMGAppRater.java
private static String ratePreferenceToString(SharedPreferences pref) { JSONObject thiz = new JSONObject(); try {/*w w w. ja va2s .c o m*/ thiz.put(DECLINED_RATE, pref.getBoolean(DECLINED_RATE, false)); thiz.put(APP_RATED, pref.getBoolean(APP_RATED, false)); thiz.put(TRACKING_VERSION, pref.getInt(TRACKING_VERSION, -1)); thiz.put(FIRST_USE, SimpleDateFormat.getDateTimeInstance().format(new Date(pref.getLong(FIRST_USE, 0L)))); thiz.put(USE_COUNT, pref.getInt(USE_COUNT, 0)); thiz.put(REMIND_LATER_DATE, SimpleDateFormat.getDateTimeInstance().format(new Date(pref.getLong(REMIND_LATER_DATE, 0L)))); } catch (JSONException exc) { LOGE(TAG, "Error creating JSON Object", exc); } return thiz.toString(); }
From source file:Main.java
public static <T extends BroadcastReceiver> void scheduleUpdate(Context context, Class<T> clazz) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, clazz); PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); Random random = new Random(System.currentTimeMillis()); long offset = random.nextLong() % (12 * 60 * 60 * 1000); long interval = (24 * 60 * 60 * 1000) + offset; String prefKey = "pref_scheduled_monitor_config_update_" + clazz.getCanonicalName(); long scheduledTime = preferences.getLong(prefKey, -1); if (scheduledTime == -1) { context.sendBroadcast(intent);/* www. jav a2 s.c o m*/ } if (scheduledTime <= System.currentTimeMillis()) { context.sendBroadcast(intent); scheduledTime = System.currentTimeMillis() + interval; preferences.edit().putLong(prefKey, scheduledTime).commit(); Log.w("PeriodicActionUtils", "Scheduling for all new time: " + scheduledTime + " (" + clazz.getSimpleName() + ")"); } else { Log.w("PeriodicActionUtils", "Scheduling for time found in preferences: " + scheduledTime + " (" + clazz.getSimpleName() + ")"); } am.cancel(sender); am.set(AlarmManager.RTC_WAKEUP, scheduledTime, sender); Log.w("PeriodicActionUtils", "Scheduled for: " + scheduledTime + " (" + clazz.getSimpleName() + ")"); }
From source file:com.google.android.apps.muzei.notifications.NewWallpaperNotificationReceiver.java
public static void maybeShowNewArtworkNotification(Context context) { ArtDetailOpenedClosedEvent adoce = EventBus.getDefault().getStickyEvent(ArtDetailOpenedClosedEvent.class); if (adoce != null && adoce.isArtDetailOpened()) { return;// w w w . j a v a2s . c om } if (!isNewWallpaperNotificationEnabled(context)) { return; } ContentResolver contentResolver = context.getContentResolver(); ArtworkSource artworkSource = MuzeiDatabase.getInstance(context).artworkDao() .getCurrentArtworkWithSourceBlocking(); if (artworkSource == null) { return; } SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); long currentArtworkId = artworkSource.artwork.id; long lastReadArtworkId = sp.getLong(PREF_LAST_READ_NOTIFICATION_ARTWORK_ID, -1); String currentImageUri = artworkSource.artwork.imageUri != null ? artworkSource.artwork.imageUri.toString() : null; String lastReadImageUri = sp.getString(PREF_LAST_READ_NOTIFICATION_ARTWORK_IMAGE_URI, null); String currentToken = artworkSource.artwork.token; String lastReadToken = sp.getString(PREF_LAST_READ_NOTIFICATION_ARTWORK_TOKEN, null); // We've already dismissed the notification if the IDs match boolean previouslyDismissedNotification = lastReadArtworkId == currentArtworkId; // We've already dismissed the notification if the image URIs match and both are not empty previouslyDismissedNotification = previouslyDismissedNotification || (!TextUtils.isEmpty(lastReadImageUri) && !TextUtils.isEmpty(currentImageUri) && TextUtils.equals(lastReadImageUri, currentImageUri)); // We've already dismissed the notification if the tokens match and both are not empty previouslyDismissedNotification = previouslyDismissedNotification || (!TextUtils.isEmpty(lastReadToken) && !TextUtils.isEmpty(currentToken) && TextUtils.equals(lastReadToken, currentToken)); if (previouslyDismissedNotification) { return; } Bitmap largeIcon; Bitmap background; try { BitmapFactory.Options options = new BitmapFactory.Options(); // Check if there's rotation int rotation = 0; try (InputStream in = contentResolver.openInputStream(MuzeiContract.Artwork.CONTENT_URI)) { if (in == null) { return; } ExifInterface exifInterface = new ExifInterface(in); int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: rotation = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: rotation = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: rotation = 270; break; } } catch (IOException | NumberFormatException | StackOverflowError e) { Log.w(TAG, "Couldn't open EXIF interface on artwork", e); } BitmapRegionLoader regionLoader = BitmapRegionLoader .newInstance(contentResolver.openInputStream(MuzeiContract.Artwork.CONTENT_URI), rotation); int width = regionLoader.getWidth(); int height = regionLoader.getHeight(); int shortestLength = Math.min(width, height); options.inJustDecodeBounds = false; int largeIconHeight = context.getResources() .getDimensionPixelSize(android.R.dimen.notification_large_icon_height); options.inSampleSize = ImageUtil.calculateSampleSize(shortestLength, largeIconHeight); largeIcon = regionLoader.decodeRegion(new Rect(0, 0, width, height), options); // Use the suggested 400x400 for Android Wear background images per // http://developer.android.com/training/wearables/notifications/creating.html#AddWearableFeatures options.inSampleSize = ImageUtil.calculateSampleSize(height, 400); background = regionLoader.decodeRegion(new Rect(0, 0, width, height), options); } catch (IOException e) { Log.e(TAG, "Unable to load artwork to show notification", e); return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { createNotificationChannel(context); } String artworkTitle = artworkSource.artwork.title; String title = TextUtils.isEmpty(artworkTitle) ? context.getString(R.string.app_name) : artworkTitle; NotificationCompat.Builder nb = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL) .setSmallIcon(R.drawable.ic_stat_muzei) .setColor(ContextCompat.getColor(context, R.color.notification)) .setPriority(NotificationCompat.PRIORITY_MIN).setAutoCancel(true).setContentTitle(title) .setContentText(context.getString(R.string.notification_new_wallpaper)).setLargeIcon(largeIcon) .setContentIntent(PendingIntent.getActivity(context, 0, context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()), PendingIntent.FLAG_UPDATE_CURRENT)) .setDeleteIntent(PendingIntent.getBroadcast(context, 0, new Intent(context, NewWallpaperNotificationReceiver.class) .setAction(ACTION_MARK_NOTIFICATION_READ), PendingIntent.FLAG_UPDATE_CURRENT)); NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle().bigLargeIcon(null) .setBigContentTitle(title).setSummaryText(artworkSource.artwork.byline).bigPicture(background); nb.setStyle(style); NotificationCompat.WearableExtender extender = new NotificationCompat.WearableExtender(); // Support Next Artwork if (artworkSource.supportsNextArtwork) { PendingIntent nextPendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(context, NewWallpaperNotificationReceiver.class).setAction(ACTION_NEXT_ARTWORK), PendingIntent.FLAG_UPDATE_CURRENT); nb.addAction(R.drawable.ic_notif_next_artwork, context.getString(R.string.action_next_artwork_condensed), nextPendingIntent); // Android Wear uses larger action icons so we build a // separate action extender.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_notif_full_next_artwork, context.getString(R.string.action_next_artwork_condensed), nextPendingIntent) .extend(new NotificationCompat.Action.WearableExtender().setAvailableOffline(false)) .build()); } List<UserCommand> commands = artworkSource.commands; // Show custom actions as a selectable list on Android Wear devices if (!commands.isEmpty()) { String[] actions = new String[commands.size()]; for (int h = 0; h < commands.size(); h++) { actions[h] = commands.get(h).getTitle(); } PendingIntent userCommandPendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(context, NewWallpaperNotificationReceiver.class).setAction(ACTION_USER_COMMAND), PendingIntent.FLAG_UPDATE_CURRENT); RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_USER_COMMAND).setAllowFreeFormInput(false) .setLabel(context.getString(R.string.action_user_command_prompt)).setChoices(actions).build(); extender.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_notif_full_user_command, context.getString(R.string.action_user_command), userCommandPendingIntent) .addRemoteInput(remoteInput) .extend(new NotificationCompat.Action.WearableExtender().setAvailableOffline(false)) .build()); } Intent viewIntent = artworkSource.artwork.viewIntent; if (viewIntent != null) { viewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { PendingIntent nextPendingIntent = PendingIntent.getActivity(context, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT); nb.addAction(R.drawable.ic_notif_info, context.getString(R.string.action_artwork_info), nextPendingIntent); // Android Wear uses larger action icons so we build a // separate action extender.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_notif_full_info, context.getString(R.string.action_artwork_info), nextPendingIntent) .extend(new NotificationCompat.Action.WearableExtender().setAvailableOffline(false)) .build()); } catch (RuntimeException ignored) { // This is actually meant to catch a FileUriExposedException, but you can't // have catch statements for exceptions that don't exist at your minSdkVersion } } nb.extend(extender); // Hide the image and artwork title for the public version NotificationCompat.Builder publicBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL) .setSmallIcon(R.drawable.ic_stat_muzei) .setColor(ContextCompat.getColor(context, R.color.notification)) .setPriority(NotificationCompat.PRIORITY_MIN).setAutoCancel(true) .setContentTitle(context.getString(R.string.app_name)) .setContentText(context.getString(R.string.notification_new_wallpaper)) .setContentIntent(PendingIntent.getActivity(context, 0, context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()), PendingIntent.FLAG_UPDATE_CURRENT)) .setDeleteIntent(PendingIntent.getBroadcast(context, 0, new Intent(context, NewWallpaperNotificationReceiver.class) .setAction(ACTION_MARK_NOTIFICATION_READ), PendingIntent.FLAG_UPDATE_CURRENT)); nb.setPublicVersion(publicBuilder.build()); NotificationManagerCompat nm = NotificationManagerCompat.from(context); nm.notify(NOTIFICATION_ID, nb.build()); }
From source file:com.appsimobile.appsii.module.weather.WeatherLoadingService.java
/** * Returns true when the interval to request a sync has been expired. * Normally this is determined in the sync adapter mechanism itself. * But if it decides to stop syncing correctly, this method can * determine if now would be a good time to call * {@link ContentResolver#requestSync(Account, String, Bundle)} to * make sure the weather data is up to date. * <p/>//w w w.j ava 2s .co m * Returns true when now is a good time to update the weatherdata. */ public static boolean hasTimeoutExpired(SharedPreferences preferences) { long lastUpdate = preferences.getLong(PREFERENCE_LAST_UPDATED_MILLIS, 0); long timePassedMillis = System.currentTimeMillis() - lastUpdate; long minutesPassed = timePassedMillis / DateUtils.MINUTE_IN_MILLIS; return minutesPassed > 45; }
From source file:io.rapidpro.androidchannel.RapidPro.java
public static void broadcastUpdatedCounts(Context context) { Intent intent = new Intent(); intent.setAction(Intents.UPDATE_COUNTS); intent.addCategory(Intent.CATEGORY_DEFAULT); int sent = RapidPro.get().getTotalSent(); int capacity = RapidPro.get().getSendCapacity(); int outgoing = DBCommandHelper.getCommandCount(context, DBCommandHelper.IN, DBCommandHelper.BORN, MTTextMessage.CMD)/*from ww w.j a v a 2 s. co m*/ + DBCommandHelper.getCommandCount(context, DBCommandHelper.IN, MTTextMessage.PENDING, MTTextMessage.CMD); int incoming = DBCommandHelper.getMessagesReceivedInWindow(context); int retry = DBCommandHelper.getCommandCount(context, DBCommandHelper.IN, MTTextMessage.RETRY, MTTextMessage.CMD); int sync = DBCommandHelper.getCommandCount(context, DBCommandHelper.OUT, DBCommandHelper.BORN, null); intent.putExtra(Intents.SENT_EXTRA, sent); intent.putExtra(Intents.CAPACITY_EXTRA, capacity); intent.putExtra(Intents.OUTGOING_EXTRA, outgoing); intent.putExtra(Intents.INCOMING_EXTRA, incoming); intent.putExtra(Intents.RETRY_EXTRA, retry); intent.putExtra(Intents.SYNC_EXTRA, sync); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); intent.putExtra(Intents.CONNECTION_UP_EXTRA, prefs.getBoolean(SettingsActivity.CONNECTION_UP, true)); intent.putExtra(Intents.LAST_SMS_SENT, prefs.getLong(SettingsActivity.LAST_SMS_SENT, 0)); intent.putExtra(Intents.LAST_SMS_RECEIVED, prefs.getLong(SettingsActivity.LAST_SMS_RECEIVED, 0)); intent.putExtra(Intents.IS_PAUSED, prefs.getBoolean(SettingsActivity.IS_PAUSED, false)); context.sendBroadcast(intent); }
From source file:com.smarthome.deskclock.Alarms.java
/** * If there is a snooze set, enable it in AlarmManager * @return true if snooze is set// w ww . j a va 2 s .c o m */ private static boolean enableSnoozeAlert(final Context context) { SharedPreferences prefs = context.getSharedPreferences(AlarmClock.PREFERENCES, 0); int id = prefs.getInt(PREF_SNOOZE_ID, -1); if (id == -1) { return false; } long time = prefs.getLong(PREF_SNOOZE_TIME, -1); // Get the alarm from the db. final Alarm alarm = getAlarm(context.getContentResolver(), id); if (alarm == null) { return false; } // The time in the database is either 0 (repeating) or a specific time // for a non-repeating alarm. Update this value so the AlarmReceiver // has the right time to compare. alarm.time = time; enableAlert(context, alarm, time); return true; }
From source file:com.stockita.popularmovie.utility.Utilities.java
/** * This method to get the current time in millis that stored last time sync, so * we will delete all the rows that has this time stamp. */// w w w . j av a 2s .co m public static long getTimeStamp(Context context, String key) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); return prefs.getLong(key, 0); }
From source file:edu.rowan.app.fragments.FoodRatingFragment.java
/** * Start pre-fetching data (load data before it is needed) * // ww w . jav a 2 s .com * @param reference Activity reference required for AQuery */ public static void prefetch(Activity reference, boolean updateCache, FoodRatingFragment callback) { SharedPreferences prefs = reference.getSharedPreferences(FoodRatingFragment.PREFS, 0); if (!prefs.contains(FoodRatingFragment.USER_ID)) { // we need to get a userId getUserID(reference); } long lastUpdate = prefs.getLong(LAST_REFRESH, 0); // [difference] / (milis * seconds * minutes) int hourDifference = (int) (Calendar.getInstance().getTimeInMillis() - lastUpdate) / (1000 * 60 * 60); Log.d("FoodRatingFragment", "Hour difference: " + hourDifference); if (updateCache || hourDifference > UPDATE_INTERVAL || lastUpdate == 0) { Log.d("FoodRatingFragment", "Fetching Ratings"); fetchAllRatings(reference, callback); } else { Log.d("FoodRatingFragment", "Cached food ratings"); Log.d("Marketplace", prefs.getString(Integer.toString(prefs.getInt(TYPE_MARKETPLACE, 0)), "CACHE FAIL")); Log.d("Smokehouse", prefs.getString(Integer.toString(prefs.getInt(TYPE_SMOKEHOUSE, 0)), "CACHE FAIL")); } }
From source file:de.spiritcroc.modular_remote.Util.java
public static long getPageId(Context context) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); long lastId = sharedPreferences.getLong(Preferences.LAST_PAGE_ID, -1); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putLong(Preferences.LAST_PAGE_ID, ++lastId).apply(); return lastId; }