Beispiel #1
1
  public void alarmFacebookUserComming(Message callbackMessage) {
    Log.d(TAG, "alarmFacebookUserComming");

    Message msg = handler.obtainMessage(FACEBOOK_FRIENDS_GET);
    if (callbackMessage != null) {
      msg.getData().putParcelable(CALLBACK, callbackMessage);
      msg.getData().putLong("hisuid", callbackMessage.getData().getLong("hisuid", -1));
    }
    handler.sendMessageDelayed(msg, 1 * 1000);

    long nexttime = System.currentTimeMillis() + getFriendsTimeout() * 1000L;

    if (SNSService.TEST_LOOP) {
      nexttime = System.currentTimeMillis() + 90 * 1000;
    }

    AlarmManager alarmMgr = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);

    Intent i = new Intent();
    i.setClassName("com.ast.free", "com.ast.free.service.SNSService");
    i.setAction("com.ast.free.intent.action.FACEBOOK_USER");
    PendingIntent userpi =
        PendingIntent.getService(
            mContext.getApplicationContext(), 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
    alarmMgr.set(AlarmManager.RTC_WAKEUP, nexttime, userpi);
  }
Beispiel #2
0
 private void createMonitorAlarm() {
   AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
   Intent intent = new Intent(this, MonitoringAlarmReceiver.class);
   PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
   // the monitoring alarm will schedule another alarm once it's finished
   alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pendingIntent);
 }
  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {

    // Hotkeys
    if (keyCode == KeyEvent.KEYCODE_BACK) {

      // If the new interval != the old interval, we got to restart the
      // "alarm"
      if (originalInterval != sharedPreferences.getInt(Constants.SP_BL_INTERVAL_SERVICE, 0)) {

        // Get the interval
        int serviceInterval =
            sharedPreferences.getInt(
                    Constants.SP_BL_INTERVAL_SERVICE, (Constants.HOUR_IN_SECONDS / 2))
                * 1000;

        // Restart the AlarmManager
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        PendingIntent pendingIntent =
            PendingIntent.getService(this, 0, new Intent(this, BattlelogService.class), 0);
        alarmManager.cancel(pendingIntent);
        alarmManager.setInexactRepeating(
            AlarmManager.ELAPSED_REALTIME, 0, serviceInterval, pendingIntent);

        Log.d(
            Constants.DEBUG_TAG,
            "Setting the service to update every " + serviceInterval / 60000 + " minutes");
      }
      startActivity(new Intent(this, DashboardActivity.class));
      finish();
      return true;
    }

    return super.onKeyDown(keyCode, event);
  }
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i(TAG, "onStartCommand");

    // @TODO should test if startCommand is from autolaunch on boot -> then if yes, check if
    // CordovaStepCounter.ACTION_START has really been called or die
    Log.i(TAG, "- Relaunch service in 1 hour (4.4.2 start_sticky bug ) : ");
    Intent newServiceIntent = new Intent(this, StepCounterService.class);
    AlarmManager aManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    PendingIntent stepIntent =
        PendingIntent.getService(
            getApplicationContext(), 10, newServiceIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    // PendingIntent.GetService (ApplicationContext, 10, intent2, PendingIntentFlags.UpdateCurrent);

    aManager.set(
        AlarmManager.RTC, java.lang.System.currentTimeMillis() + 1000 * 60 * 60, stepIntent);

    if (isRunning /* || has no step sensors */) {
      Log.i(TAG, "Not initialising sensors");
      return Service.START_STICKY;
    }

    Log.i(TAG, "Initialising sensors");
    doInit();

    isRunning = true;
    return Service.START_STICKY;
  }
Beispiel #5
0
 private static void clearReminder(Context context) {
   Intent alarmIntent = new Intent(ReminderReceiver.REMINDER_ACTION);
   PendingIntent pendingIntent =
       PendingIntent.getBroadcast(context, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
   AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
   alarmManager.cancel(pendingIntent);
 }
  public void rescheduleNotificationSync(boolean force) {
    AlarmManager alarmMgr = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
    long nexttime;

    long current_time = System.currentTimeMillis();
    long last_sync_time = orm.getNotificationLastTime();
    long donespan = (current_time - last_sync_time);
    long left_time = Long.valueOf(orm.getNotificationInterval()) * sync_period - donespan;
    if (donespan < 0 || left_time <= 0) {
      long waittime = 1;
      for (int i = 0; i < nErrorCount && i < 10; i++) {
        waittime = waittime * 2;
      }
      nexttime = System.currentTimeMillis() + 1 * 60 * 1000 * waittime;
    } else {
      nexttime = System.currentTimeMillis() + left_time;
    }

    if (force == true) {
      nexttime = System.currentTimeMillis() + 1 * 60 * 1000;
    }

    if (SNSService.TEST_LOOP) {
      nexttime = System.currentTimeMillis() + 1 * 60 * 1000;
    }

    Intent i = new Intent();
    i.setClassName("oms.sns.facebook", SERVICE);
    i.setAction(ACTION);
    PendingIntent phonebookpi =
        PendingIntent.getService(
            mContext.getApplicationContext(), 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
    alarmMgr.set(AlarmManager.RTC_WAKEUP, nexttime, phonebookpi);
  }
 public void setOnetimeTimer(Context context) {
   AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
   Intent intent = new Intent(context, AlarmBroadcastListener.class);
   intent.putExtra(ONE_TIME, Boolean.TRUE);
   PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
   am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pi);
 }
 public void cancelAlarm(Context context) {
   Log.d(TAG, "cancelAlarm() called with: " + "context = [" + context + "]");
   Intent intent = new Intent(context, LibraryRenewAlarmBroadcastReceiver.class);
   PendingIntent sender = PendingIntent.getBroadcast(context, 1, intent, 0);
   AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
   alarmManager.cancel(sender);
 }
 private void refresh() {
   Intent intent = new Intent(this, SplashActivity.class); // CampusdishclientActivity.class);
   PendingIntent p = PendingIntent.getActivity(this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
   AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
   mgr.set(AlarmManager.RTC, System.currentTimeMillis(), p);
   System.exit(0);
 }
Beispiel #10
0
  /**
   * Schedules alarms for a single task
   *
   * @param shouldPerformPropertyCheck whether to check if task has requisite properties
   */
  @SuppressWarnings("nls")
  private void scheduleAlarm(Metadata alarm) {
    if (alarm == null) return;

    long taskId = alarm.getValue(Metadata.TASK);
    int type = ReminderService.TYPE_ALARM;

    Context context = ContextManager.getContext();
    Intent intent = new Intent(context, Notifications.class);
    intent.setType("ALARM" + Long.toString(taskId)); // $NON-NLS-1$
    intent.setAction(Integer.toString(type));
    intent.putExtra(Notifications.ID_KEY, taskId);
    intent.putExtra(Notifications.TYPE_KEY, type);

    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

    long time = alarm.getValue(AlarmFields.TIME);
    if (time == 0 || time == NO_ALARM) am.cancel(pendingIntent);
    else if (time > DateUtilities.now()) {
      if (Constants.DEBUG)
        Log.e("Astrid", "Alarm (" + taskId + ", " + type + ") set for " + new Date(time));
      am.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
    }
  }
 /**
  * This method will stop the periodic updates, but only stops the updates if no Challenges are
  * active. This method can be called, when the app is closed.
  *
  * <p>To force a stop of the Updates, set the flag forceStop true. This can be used when no
  * network access is available.
  *
  * @param forceStop Stops the periodic updates, even if tracking is active.
  */
 public void requestStopUpdates(boolean forceStop) {
   if (forceStop || (challengeData.activeChallengeCount() == 0)) {
     AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
     alarmManager.cancel(updaterPendingIntent);
     Log.d(TAG, "stoping periodic updates now");
   }
 }
Beispiel #12
0
 private void stopLogicService() {
   PendingIntent pintent =
       PendingIntent.getService(
           LogicActivity.this, 0, new Intent(LogicActivity.this, LogicService.class), 0);
   AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
   alarm.cancel(pintent);
 }
Beispiel #13
0
 /**
  * Run the notification service delayed by a minute to display and (re)schedule upcoming episode
  * alarms.
  */
 public static void runNotificationServiceDelayed(Context context) {
   AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
   Intent i = new Intent(context, OnAlarmReceiver.class);
   PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
   am.set(
       AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1 * DateUtils.MINUTE_IN_MILLIS, pi);
 }
  private void setUpNewAlarm() {
    // get todays date
    Calendar cal = Calendar.getInstance();
    // get current month
    int currentMonth = cal.get(Calendar.MONTH);
    // move month ahead
    currentMonth++;
    // check if has not exceeded threshold of december
    if (currentMonth > Calendar.DECEMBER) {
      // alright, reset month to jan and forward year by 1 e.g fro 2013 to 2014
      currentMonth = Calendar.JANUARY;
      // Move year ahead as well
      cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) + 1);
    }
    // reset calendar to next month
    cal.set(Calendar.MONTH, currentMonth);

    // cal is set, now create new alarm for next month
    // Set intent to be broadcast for reminder
    Intent intent = new Intent(getApplicationContext(), OverheadReceiver.class);
    PendingIntent pendingIntent =
        PendingIntent.getBroadcast(
            getApplicationContext(),
            cal.get(Calendar.DAY_OF_MONTH),
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    // Set AlarmManager to trigger broadcast
    AlarmManager alarmManager =
        (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC, cal.getTimeInMillis(), pendingIntent);
  }
Beispiel #15
0
    @Override
    public void run() {
      try {
        int warn = refreshData(_mContext);
        Intent broadcastIntent = new Intent(REFRESH_BROADCAST_MESSAGE);
        _mContext.sendBroadcast(broadcastIntent);

        if (warn > 0 && warn >= Preferences.getWarnLevel(_mContext)) {
          Notifier.showNotification(_mContext, warn);
        } else if (warn == ITerminal.STATE_OK) Notifier.hideNotification(_mContext, false);

        long interval = Preferences.getUpdateInterval(_mContext);
        if (interval == 0) return;
        AlarmManager alarmManager =
            (AlarmManager) _mContext.getSystemService(Context.ALARM_SERVICE);
        Intent startIntent = new Intent(_mContext, StatesReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(_mContext, 0, startIntent, 0);
        alarmManager.set(
            AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + interval,
            pendingIntent);
      } finally {
        _mWakeLock.release();
      }
    }
  /** Schedules an alarm to go off a few minutes before this talk. */
  private void scheduleNotification(Talk talk) {
    // We need to know the time slot of the talk, so fetch its data if we haven't already.
    if (!talk.isDataAvailable()) {
      Talk.getInBackground(
          talk.getObjectId(),
          new GetCallback<Talk>() {
            @Override
            public void done(Talk talk, ParseException e) {
              if (talk != null) {
                scheduleNotification(talk);
              }
            }
          });
      return;
    }

    // Figure out what time we need to set the alarm for.
    Date talkStart = null != talk.getSlot() ? talk.getSlot().getStartTime() : null;
    if (BuildConfig.DEBUG) {
      Logger.getLogger(getClass().getName()).log(Level.INFO, "Registering alarm for " + talkStart);
    }
    long fiveMinutesBefore = null != talkStart ? talkStart.getTime() - (5000 * 60) : Long.MAX_VALUE;
    if (fiveMinutesBefore < System.currentTimeMillis()) {
      return;
    }

    // Register the actual alarm.
    AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingIntent = getPendingIntent(talk);
    manager.set(AlarmManager.RTC_WAKEUP, fiveMinutesBefore, pendingIntent);
  }
  @Kroll.method
  public void cancelAlarmService(@Kroll.argument(optional = true) Object requestCode) {
    // To cancel an alarm the signature needs to be the same as the submitting one.
    utils.infoLog("Cancelling Alarm Service");
    int intentRequestCode = AlarmmanagerModule.DEFAULT_REQUEST_CODE;
    if (requestCode != null) {
      if (requestCode instanceof Number) {
        intentRequestCode = ((Number) requestCode).intValue();
      }
    }

    // Create a placeholder for the args value
    HashMap<String, Object> placeholder = new HashMap<String, Object>(0);
    KrollDict args = new KrollDict(placeholder);

    // Create the Alarm Manager
    AlarmManager am =
        (AlarmManager)
            TiApplication.getInstance()
                .getApplicationContext()
                .getSystemService(TiApplication.ALARM_SERVICE);
    Intent intent = createAlarmServiceIntent(args);
    PendingIntent sender =
        PendingIntent.getBroadcast(
            TiApplication.getInstance().getApplicationContext(),
            intentRequestCode,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    am.cancel(sender);
    utils.infoLog("Alarm Service Canceled");
  }
  private synchronized void cleanUp() {
    Logger.d("Service cleanUp called");
    this.taskQueue.clear();

    if (this.currentTask != null) {
      this.currentTask.stop();
    }
    // remove all future tasks
    this.measurementExecutor.shutdown();
    // remove and stop all active tasks
    this.measurementExecutor.shutdownNow();
    this.checkin.shutDown();

    this.unregisterReceiver(broadcastReceiver);
    Logger.d("canceling pending intents");

    if (checkinIntentSender != null) {
      checkinIntentSender.cancel();
      alarmManager.cancel(checkinIntentSender);
    }
    if (checkinRetryIntentSender != null) {
      checkinRetryIntentSender.cancel();
      alarmManager.cancel(checkinRetryIntentSender);
    }
    if (measurementIntentSender != null) {
      measurementIntentSender.cancel();
      alarmManager.cancel(measurementIntentSender);
    }
    persistState();
    this.notifyAll();
    phoneUtils.shutDown();
    Logger.i("Shut down all executors and stopping service");
  }
  private static void setAlarm(final Context context, final String reminder_time) {
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, DevotionReminderReceiver.class);
    PendingIntent pi =
        PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    // always cancel current (if any)
    am.cancel(pi);

    if (TextUtils.isEmpty(reminder_time)) {
      return;
    }

    int hour = Integer.parseInt(reminder_time.substring(0, 2));
    int minute = Integer.parseInt(reminder_time.substring(2, 4));
    Calendar c = GregorianCalendar.getInstance();
    c.set(Calendar.HOUR_OF_DAY, hour);
    c.set(Calendar.MINUTE, minute);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);

    if (c.getTimeInMillis() < System.currentTimeMillis()) {
      c.add(Calendar.DAY_OF_YEAR, 1);
    }

    am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
  }
Beispiel #20
0
 public static void startServiceAlarm(Context context, Class<?> service, long interval) {
   AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
   Intent i = new Intent(context, service);
   PendingIntent p =
       PendingIntent.getService(context, REQUEST_CODE, i, PendingIntent.FLAG_CANCEL_CURRENT);
   am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, 0, interval, p);
 }
  /** Start the notification service call the notification every 5 mins */
  public void startNotificationService() {

    //		Intent it = new Intent();
    //		it.setClass(this, NotificationService.class);
    //		startService(it);

    CommonApplication.debug("I am startNotificationService");
    // set the alarm to run periodly
    PendingIntent mAlarmSender =
        PendingIntent.getService(
            getApplicationContext(),
            0,
            new Intent(getApplicationContext(), NotificationService.class),
            0);

    CommonApplication.debug("I am starting the ns!");
    long firstTime = SystemClock.elapsedRealtime();

    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    // this code is unvaild under xiaomi phone
    // am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime,
    // 1 * 1000, mAlarmSender);

    // make time related to system time so that can wake up from sleep
    am.setRepeating(AlarmManager.RTC_WAKEUP, firstTime, 2 * 60 * 1000, mAlarmSender);
    // check every three minutes!

  }
Beispiel #22
0
 public static void stopServiceAlarm(Context context, Class<?> service) {
   AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
   Intent i = new Intent(context, service);
   PendingIntent p =
       PendingIntent.getService(context, REQUEST_CODE, i, PendingIntent.FLAG_CANCEL_CURRENT);
   am.cancel(p);
 }
  public static void setAlarm(Context context) {
    SharedPreferences prefs = AnonymousStats.getPreferences(context);
    if (prefs.contains(AnonymousStats.ANONYMOUS_OPT_IN)) {
      migrate(context, prefs);
    }
    if (!Utilities.isStatsCollectionEnabled(context)) {
      initiateOptOut(context);
      return;
    }
    long lastSynced = prefs.getLong(AnonymousStats.ANONYMOUS_LAST_CHECKED, 0);
    if (lastSynced == 0) {
      launchService(context, true); // service will reschedule the next alarm
      return;
    }
    long millisFromNow = (lastSynced + UPDATE_INTERVAL) - System.currentTimeMillis();

    Intent intent = new Intent(ACTION_LAUNCH_SERVICE);
    intent.setClass(context, ReportingServiceManager.class);

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(
        AlarmManager.RTC_WAKEUP,
        System.currentTimeMillis() + millisFromNow,
        PendingIntent.getBroadcast(context, 0, intent, 0));
    Log.d(TAG, "Next sync attempt in : " + (millisFromNow / MILLIS_PER_HOUR) + " hours");
  }
  @Override
  public final void onReceive(final Context context, final Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {

      SharedPreferences sharedPreferences =
          context.getSharedPreferences(WeatherSettings.WEATHER_SETTING, 0);
      boolean reset = sharedPreferences.getBoolean(WeatherSettings.RESET_KEY, false);

      Intent service = new Intent(context, ActionBootService.class);
      startWakefulService(context, service);

      if (reset == true) {
        Calendar myCal = Calendar.getInstance();
        myCal.set(Calendar.HOUR_OF_DAY, MainActivity.RESET_HOUR);
        myCal.set(Calendar.MINUTE, MainActivity.RESET_MINUTE);

        Intent someIntent = new Intent(context.getApplicationContext(), ResetAlarmReceiver.class);
        PendingIntent pendingIntent =
            PendingIntent.getBroadcast(
                context.getApplicationContext(), MainActivity.REPEATING, someIntent, 0);

        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP, myCal.getTimeInMillis(), pendingIntent);
      }
    }
  }
  @Override
  public void onReceive(Context context, Intent intent) {

    Log.i("WifiO", "RecvTempDisable");

    LogWO logg = new LogWO(context);
    logg.log("WifiOpti Service disabled for 5m");

    SharedPreferences sett = context.getSharedPreferences("WifiOpti", 2);
    SharedPreferences.Editor settEditor = sett.edit();

    settEditor.putBoolean("WifiOptiServiced", false);
    settEditor.putBoolean("WifiOptiTempDisabled", true);
    settEditor.commit();

    // Turn off service
    Intent serviceIntent = new Intent(context, WifiOptiService.class);
    context.stopService(serviceIntent);

    // Schedule restart
    Intent alarmIntent = new Intent(context, RecvTempResume.class);
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(System.currentTimeMillis());
    cal.add(Calendar.MINUTE, 5);

    Log.d("WifiO", " -> " + cal.getTime().toString());

    am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
  }
 public static void setReminder(
     Context context,
     long id,
     String title,
     long dueDate,
     long listId,
     long reminderDate,
     long reminderInterval) {
   String actionName = context.getResources().getString(R.string.intent_action_alarm);
   Intent alarmIntent = new Intent(actionName);
   alarmIntent.putExtra(NotificationUtils.ID, id);
   alarmIntent.putExtra(NotificationUtils.TITLE, title);
   alarmIntent.putExtra(NotificationUtils.DUE_DATE, dueDate);
   alarmIntent.putExtra(NotificationUtils.LIST_ID, listId);
   PendingIntent alarmPendingIntent =
       PendingIntent.getBroadcast(context, getNotificationId(id), alarmIntent, 0);
   AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
   if (reminderInterval > 0) {
     alarmManager.setRepeating(
         AlarmManager.RTC_WAKEUP, reminderDate, reminderInterval, alarmPendingIntent);
     if (Log.LOGV) Log.v("TaskDetailDialog set recurring reminder at " + dueDate);
   } else {
     alarmManager.set(AlarmManager.RTC_WAKEUP, reminderDate, alarmPendingIntent);
     if (Log.LOGV) Log.v("TaskDetailDialog set reminder at " + dueDate);
   }
 }
Beispiel #27
0
  public void rescheduleFacebookUser(boolean force) {
    AlarmManager alarmMgr = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
    long nexttime;

    long current_time = System.currentTimeMillis();
    long last_update_time = orm.getLastUpdateFriendTime();
    long donespan = (current_time - last_update_time);
    long left_time = getFriendsTimeout() * 1000L - donespan;
    if (donespan < 0 || left_time <= 0) {
      long waittime = 1;
      for (int i = 0; i < nErrorCount && i < 10; i++) {
        waittime = waittime * 2;
      }
      nexttime = System.currentTimeMillis() + 10 * 1000 * waittime;
    } else {
      nexttime = System.currentTimeMillis() + left_time;
    }

    if (force == true) {
      nexttime = System.currentTimeMillis() + 10 * 1000;
    }

    if (SNSService.TEST_LOOP) {
      nexttime = System.currentTimeMillis() + 90 * 1000;
    }

    Intent i = new Intent();
    i.setClassName("com.ast.free", "com.ast.free.service.SNSService");
    i.setAction("com.ast.free.intent.action.FACEBOOK_USER");
    PendingIntent userpi =
        PendingIntent.getService(
            mContext.getApplicationContext(), 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
    alarmMgr.set(AlarmManager.RTC_WAKEUP, nexttime, userpi);
  }
  @Override
  public void onClick(View v) {
    int id = v.getId();
    switch (id) {
        // stop button listener press
      case R.id.StopButton:
        {
          // to cancel notification
          mNotificationManager.cancel(1);

          // to stop the alarm from repeating
          Intent intent = new Intent(this, StopAlarm.class);
          PendingIntent sender = PendingIntent.getActivity(this, notiRequestCode, intent, 0);
          AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
          am.cancel(sender);
          Toast.makeText(getBaseContext(), " alarm stopped", Toast.LENGTH_LONG).show();
          try {
            boolean test =
                new DeleteReminderNotiCode().execute(Integer.toString(notiRequestCode)).get();
          } catch (Exception ex) {
            ex.printStackTrace();
          }
          // after stopping the alarm, it will redirect you to the main reminder page
          Intent transferintent = new Intent(this, Reminder.class);
          transferintent.putExtra("passuser", user);
          transferintent.putExtra("inputCode", inputCode);
          startActivity(transferintent);
        }
    }
  }
  // 2016-03-29 시청예약시 데이타베이스 처리를 programId 로 하는데 서버에서 programId를 중복으로 보내고 있다
  // 그래서 시청시간을 추가함.
  public void removeWatchTvReserveAlarmWithProgramIdAndStartTime(
      String programId, String startTime) {
    int iSeq = 0;
    Realm realm = Realm.getInstance(mContext);
    realm.beginTransaction();
    RealmResults<WatchTvObject> results =
        mRealm
            .where(WatchTvObject.class)
            .equalTo("sProgramId", programId)
            .equalTo("sProgramBroadcastingStartTime", startTime)
            .findAll();
    if (results.size() > 0) {
      WatchTvObject obj = results.get(0);
      iSeq = obj.getiSeq();
      obj.removeFromRealm();
    } else {
      //
    }
    realm.commitTransaction();

    AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(mContext, WatchTvAlarmBroadcastReceiver.class);
    PendingIntent pendingIntent =
        PendingIntent.getBroadcast(mContext, iSeq, intent, PendingIntent.FLAG_NO_CREATE);
    if (pendingIntent != null) {
      alarmManager.cancel(pendingIntent);
      pendingIntent.cancel();
    }
  }
  /*
   * It is not the alarm that matters
   * but the pending intent.
   * Even with a repeating alarm for an intent,
   * if you schedule the same intent again
   * for one time, the later one takes affect.
   *
   * It is as if you are setting the
   * alarm on an existing intent multiple
   * times and not the other way around.
   */
  public void alarmIntentPrimacy() {
    Calendar cal = Utils.getTimeAfterInSecs(30);
    String s = Utils.getDateTimeString(cal);
    this.mReportTo.reportBack(
        tag, "Schdeduling Repeating alarm in 5 sec interval starting at: " + s);

    // Get an intent to invoke
    // TestReceiver class
    Intent intent = new Intent(this.mContext, TestReceiver.class);
    intent.putExtra("message", "Repeating Alarm");

    PendingIntent pi = getDistinctPendingIntent(intent, 0);
    AlarmManager am = (AlarmManager) this.mContext.getSystemService(Context.ALARM_SERVICE);

    this.mReportTo.reportBack(tag, "Setting a repeat alarm 5 secs duration");
    am.setRepeating(
        AlarmManager.RTC_WAKEUP,
        cal.getTimeInMillis(),
        5 * 1000, // 5 secs
        pi);

    this.mReportTo.reportBack(tag, "Setting a onetime alarm on the same intent");
    am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pi);
    this.mReportTo.reportBack(tag, "The later alarm, one time one, takes precedence");
  }