Code example for Random

Methods: nextLong

0
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    AlarmManager am               = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent                 = new Intent(context, DirectoryUpdateReceiver.class);
    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;
    long scheduledTime            = preferences.getLong("pref_scheduled_directory_update", -1);
 
    if (scheduledTime == -1 || scheduledTime <= System.currentTimeMillis()) {
      scheduledTime = System.currentTimeMillis() + interval;
      preferences.edit().putLong("pref_scheduled_directory_update", scheduledTime).commit();
      Log.w("DirectoryUpdateReceiver", "Scheduling for all new time: " + scheduledTime);
    } else { 
      Log.w("DirectoryUpdateReceiver", "Scheduling for time found in preferences: " +
            scheduledTime);
    } 
 
    am.cancel(sender);
    am.set(AlarmManager.RTC_WAKEUP, scheduledTime, sender);