Example usage for android.app PendingIntent FLAG_CANCEL_CURRENT

List of usage examples for android.app PendingIntent FLAG_CANCEL_CURRENT

Introduction

In this page you can find the example usage for android.app PendingIntent FLAG_CANCEL_CURRENT.

Prototype

int FLAG_CANCEL_CURRENT

To view the source code for android.app PendingIntent FLAG_CANCEL_CURRENT.

Click Source Link

Document

Flag indicating that if the described PendingIntent already exists, the current one should be canceled before generating a new one.

Usage

From source file:goo.TeaTimer.TimerActivity.java

/**
 * Starts the timer at the given time// w w w .  j  ava2  s.co  m
 * @param time with which to count down
 * @param service whether or not to start the service as well
 */
private void timerStart(int time, boolean service) {
    if (LOG)
        Log.v(TAG, "Starting the timer...");

    // Star external service
    enterState(RUNNING);

    if (service) {
        if (LOG)
            Log.v(TAG, "Starting the timer service ...");
        Intent intent = new Intent(getApplicationContext(), TimerReceiver.class);
        intent.putExtra("SetTime", mLastTime);
        mPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        mAlarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + time,
                mPendingIntent);
    }

    // Internal thread to properly update the GUI
    mTimer = new Timer();
    mTime = time;
    mTimer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            timerTic();
        }
    }, 0, TIMER_TIC);

    aquireWakeLock();
}

From source file:org.apps8os.motivator.ui.MainActivity.java

/**
 * Set the notifications for the first time. After this, the notifications are controlled from the settings activity.
 *///  www .j av  a2 s.  c  om
public void setNotifications() {
    // Set up notifying user to answer to the mood question
    // The time to notify the user
    Calendar notificationTime = Calendar.getInstance();
    notificationTime.set(Calendar.MINUTE, 0);
    notificationTime.set(Calendar.SECOND, 0);
    // An alarm manager for scheduling notifications
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    // Set the notification to repeat over the given time at notificationTime
    Intent notificationIntent = new Intent(this, NotificationService.class);
    notificationIntent.putExtra(NotificationService.NOTIFICATION_TYPE, NotificationService.NOTIFICATION_MOOD);
    PendingIntent pendingNotificationIntent = PendingIntent.getService(this, 0, notificationIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    alarmManager.cancel(pendingNotificationIntent);
    if (notificationTime.get(Calendar.HOUR_OF_DAY) >= 10) {
        notificationTime.add(Calendar.DATE, 1);
    }
    notificationTime.set(Calendar.HOUR_OF_DAY, 10);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, notificationTime.getTimeInMillis(),
            AlarmManager.INTERVAL_DAY, pendingNotificationIntent);

    /** Commented out for now, setting different times for the notifications.
    if (mTimeToNotify == getString(R.string.in_the_morning_value)) {
       if (notificationTime.get(Calendar.HOUR_OF_DAY) >= 10) {
    notificationTime.add(Calendar.DATE, 1);
       }
       notificationTime.set(Calendar.HOUR_OF_DAY, 10);
       alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, notificationTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingNotificationIntent);
    } else if (mTimeToNotify == getString(R.string.morning_and_evening_value)) {
       if (notificationTime.get(Calendar.HOUR_OF_DAY) >= 10 && notificationTime.get(Calendar.HOUR_OF_DAY) < 22) {
    notificationTime.set(Calendar.HOUR_OF_DAY, 22);
       } else if (notificationTime.get(Calendar.HOUR_OF_DAY) < 10) {
    notificationTime.set(Calendar.HOUR_OF_DAY, 10);
       } else {
    notificationTime.add(Calendar.DATE, 1);
    notificationTime.set(Calendar.HOUR_OF_DAY, 10);
       }
       alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, notificationTime.getTimeInMillis(), AlarmManager.INTERVAL_HALF_DAY, pendingNotificationIntent);
    } else if (mTimeToNotify == getString(R.string.every_hour_value)) {
       notificationTime.add(Calendar.HOUR_OF_DAY, 1);
       alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, notificationTime.getTimeInMillis(), AlarmManager.INTERVAL_HOUR, pendingNotificationIntent);
    }
    **/
}

From source file:fr.paug.droidcon.service.SessionAlarmService.java

private void notifySession(final long sessionStart, final long alarmOffset) {
    long currentTime = UIUtils.getCurrentTime(this);
    final long intervalEnd = sessionStart + MILLI_TEN_MINUTES;
    LOGD(TAG, "Considering notifying for time interval.");
    LOGD(TAG, "    Interval start: " + sessionStart + "=" + (new Date(sessionStart)).toString());
    LOGD(TAG, "    Interval end: " + intervalEnd + "=" + (new Date(intervalEnd)).toString());
    LOGD(TAG, "    Current time is: " + currentTime + "=" + (new Date(currentTime)).toString());
    if (sessionStart < currentTime) {
        LOGD(TAG, "Skipping session notification (too late -- time interval already started)");
        return;//w ww.j av a  2s .  com
    }

    if (!PrefUtils.shouldShowSessionReminders(this)) {
        // skip if disabled in settings
        LOGD(TAG, "Skipping session notification for sessions. Disabled in settings.");
        return;
    }

    // Avoid repeated notifications.
    if (alarmOffset == UNDEFINED_ALARM_OFFSET && UIUtils.isNotificationFiredForBlock(this,
            ScheduleContract.Blocks.generateBlockId(sessionStart, intervalEnd))) {
        LOGD(TAG, "Skipping session notification (already notified)");
        return;
    }

    final ContentResolver cr = getContentResolver();

    LOGD(TAG, "Looking for sessions in interval " + sessionStart + " - " + intervalEnd);
    Cursor c = cr.query(ScheduleContract.Sessions.CONTENT_MY_SCHEDULE_URI, SessionDetailQuery.PROJECTION,
            ScheduleContract.Sessions.STARTING_AT_TIME_INTERVAL_SELECTION,
            ScheduleContract.Sessions.buildAtTimeIntervalArgs(sessionStart, intervalEnd), null);
    int starredCount = c.getCount();
    LOGD(TAG, "# starred sessions in that interval: " + c.getCount());
    String singleSessionId = null;
    String singleSessionRoomId = null;
    ArrayList<String> starredSessionTitles = new ArrayList<String>();
    while (c.moveToNext()) {
        singleSessionId = c.getString(SessionDetailQuery.SESSION_ID);
        singleSessionRoomId = c.getString(SessionDetailQuery.ROOM_ID);
        starredSessionTitles.add(c.getString(SessionDetailQuery.SESSION_TITLE));
        LOGD(TAG, "-> Title: " + c.getString(SessionDetailQuery.SESSION_TITLE));
    }
    if (starredCount < 1) {
        return;
    }

    // Generates the pending intent which gets fired when the user taps on the notification.
    // NOTE: Use TaskStackBuilder to comply with Android's design guidelines
    // related to navigation from notifications.
    Intent baseIntent = new Intent(this, MyScheduleActivity.class);
    baseIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    TaskStackBuilder taskBuilder = TaskStackBuilder.create(this).addNextIntent(baseIntent);

    // For a single session, tapping the notification should open the session details (b/15350787)
    if (starredCount == 1) {
        taskBuilder.addNextIntent(
                new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(singleSessionId)));
    }

    PendingIntent pi = taskBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT);

    final Resources res = getResources();
    String contentText;
    int minutesLeft = (int) (sessionStart - currentTime + 59000) / 60000;
    if (minutesLeft < 1) {
        minutesLeft = 1;
    }

    if (starredCount == 1) {
        contentText = res.getString(R.string.session_notification_text_1, minutesLeft);
    } else {
        contentText = res.getQuantityString(R.plurals.session_notification_text, starredCount - 1, minutesLeft,
                starredCount - 1);
    }

    NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this)
            .setContentTitle(starredSessionTitles.get(0)).setContentText(contentText)
            //.setColor(getResources().getColor(R.color.theme_primary))
            // Note: setColor() is available in the support lib v21+.
            // We commented it out because we want the source to compile 
            // against support lib v20. If you are using support lib
            // v21 or above on Android L, uncomment this line.
            .setTicker(res.getQuantityString(R.plurals.session_notification_ticker, starredCount, starredCount))
            .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
            .setLights(SessionAlarmService.NOTIFICATION_ARGB_COLOR, SessionAlarmService.NOTIFICATION_LED_ON_MS,
                    SessionAlarmService.NOTIFICATION_LED_OFF_MS)
            .setSmallIcon(R.drawable.ic_stat_notification).setContentIntent(pi)
            .setPriority(Notification.PRIORITY_MAX).setAutoCancel(true);
    if (minutesLeft > 5) {
        notifBuilder.addAction(R.drawable.ic_alarm_holo_dark,
                String.format(res.getString(R.string.snooze_x_min), 5),
                createSnoozeIntent(sessionStart, intervalEnd, 5));
    }
    String bigContentTitle;
    if (starredCount == 1 && starredSessionTitles.size() > 0) {
        bigContentTitle = starredSessionTitles.get(0);
    } else {
        bigContentTitle = res.getQuantityString(R.plurals.session_notification_title, starredCount, minutesLeft,
                starredCount);
    }
    NotificationCompat.InboxStyle richNotification = new NotificationCompat.InboxStyle(notifBuilder)
            .setBigContentTitle(bigContentTitle);

    // Adds starred sessions starting at this time block to the notification.
    for (int i = 0; i < starredCount; i++) {
        richNotification.addLine(starredSessionTitles.get(i));
    }
    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    LOGD(TAG, "Now showing notification.");
    nm.notify(NOTIFICATION_ID, richNotification.build());
}

From source file:com.mobiperf.MeasurementScheduler.java

/** Set the interval for checkin in seconds */
public synchronized void setCheckinInterval(long interval) {
    this.checkinIntervalSec = Math.max(Config.MIN_CHECKIN_INTERVAL_SEC, interval);
    // the new checkin schedule will start in PAUSE_BETWEEN_CHECKIN_CHANGE_MSEC seconds
    checkinIntentSender = PendingIntent.getBroadcast(this, 0, new UpdateIntent("", UpdateIntent.CHECKIN_ACTION),
            PendingIntent.FLAG_CANCEL_CURRENT);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
            System.currentTimeMillis() + Config.PAUSE_BETWEEN_CHECKIN_CHANGE_MSEC, checkinIntervalSec * 1000,
            checkinIntentSender);/*from  w  w  w. jav a2s .  c  o m*/

    Logger.i("Setting checkin interval to " + interval + " seconds");
}

From source file:com.visva.voicerecorder.utils.Utils.java

public static void showNotificationAfterCalling(Context context, String phoneName, String phoneNo,
        String createdDate) {/*w w w  . j  a  v a  2s.c  o  m*/
    Resources res = context.getResources();
    String newRecord = res.getString(R.string.you_have_new_record);
    String favorite = res.getString(R.string.favourite);
    String addNote = res.getString(R.string.add_note);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_launcher).setAutoCancel(true).setContentTitle(phoneName)
            .setContentText(newRecord);
    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    builder.setSound(alarmSound);

    int isFavourite = Utils.isCheckFavouriteContactByPhoneNo(context, phoneNo);
    Bundle bundle = new Bundle();
    bundle.putString(MyCallRecorderConstant.EXTRA_PHONE_NAME, phoneName);
    bundle.putString(MyCallRecorderConstant.EXTRA_PHONE_NO, phoneNo);
    bundle.putString(MyCallRecorderConstant.EXTRA_CREATED_DATE, createdDate);
    if (isFavourite == 0) {
        //favorite intent
        Intent favoriteIntent = new Intent();
        favoriteIntent.setAction(MyCallRecorderConstant.FAVORITE_INTENT);
        favoriteIntent.putExtras(bundle);
        PendingIntent pendingFavoriteIntent = PendingIntent.getBroadcast(context,
                MyCallRecorderConstant.NOTIFICATION_ID, favoriteIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.addAction(R.drawable.ic_star_outline_white_36dp, favorite, pendingFavoriteIntent);
    }

    //Make a note intent
    Intent makeNoteIntent = new Intent();
    makeNoteIntent.setAction(MyCallRecorderConstant.MAKE_NOTE_INTENT);
    makeNoteIntent.putExtras(bundle);
    PendingIntent pendingMakeNoteIntent = PendingIntent.getBroadcast(context,
            MyCallRecorderConstant.NOTIFICATION_ID, makeNoteIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.addAction(R.drawable.ic_customer_create, addNote, pendingMakeNoteIntent);

    Intent resultIntent = new Intent(context, ActivityHome.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(ActivityHome.class);
    stackBuilder.addNextIntent(resultIntent);

    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT);
    builder.setContentIntent(resultPendingIntent);

    builder.setPriority(NotificationCompat.PRIORITY_MAX);
    builder.setWhen(0);

    NotificationManager mNotificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(MyCallRecorderConstant.NOTIFICATION_ID, builder.build());
}

From source file:com.roamprocess1.roaming4world.service.SipNotifications.java

public void showNotificationForMessage(SipMessage msg) {
    if (!CustomDistribution.supportMessaging()) {
        return;//from  www .  j  av  a 2  s.co m
    }
    //CharSequence tickerText = context.getText(R.string.instance_message);

    if (!msg.getFrom().equalsIgnoreCase(viewingRemoteFrom)) {
        String from = formatRemoteContactString(msg.getFullFrom());

        if (from.equalsIgnoreCase(msg.getFullFrom())) {
            from = msg.getDisplayName() + " " + from;
        }

        String[] msgNumber = from.split("<");
        String msNumber = msgNumber[0];

        CharSequence tickerText = buildTickerMessage(context, msNumber, msg.getBody());

        if (messageNotification == null) {
            messageNotification = new NotificationCompat.Builder(context);
            messageNotification.setSmallIcon(
                    SipUri.isPhoneNumber(msNumber) ? R.drawable.r4wlogowhitefill : R.drawable.r4wlogowhitefill);

            String tick = tickerText.toString();

            if (tick.contains("\n")) {
                String[] arr = tick.split("\n");
                tick = arr[arr.length - 1];
            }

            if (tick.contains(imagefile)) {
                String[] arr = tick.trim().split("@@");
                arr = arr[1].split("-");
                if (arr[0].equals("VID")) {
                    messageNotification.setTicker("Sent a video");
                } else if (arr[0].equals("AUD")) {
                    messageNotification.setTicker("Sent an audio");
                } else if (arr[0].equals("IMG")) {
                    messageNotification.setTicker("Sent an image");
                } else if (arr[0].equals("CON")) {
                    messageNotification.setTicker("Sent a contact");
                } else if (arr[0].equals("LOC")) {
                    messageNotification.setTicker("Sent a location");
                }
            } else {
                messageNotification.setTicker("Sent a message");
            }

            System.out.println("Tick==" + tick);

            messageNotification.setWhen(System.currentTimeMillis());
            messageNotification.setDefaults(Notification.DEFAULT_ALL);
            messageNotification.setAutoCancel(true);
            messageNotification.setOnlyAlertOnce(true);
        }

        Intent notificationIntent = new Intent(context, MessageActivity.class);
        System.out.println("msg.getFrom()   ==" + msg.getFrom() + " " + msg.getBody());

        notificationIntent.putExtra(SipMessage.FIELD_FROM, msg.getFrom());
        notificationIntent.putExtra(SipMessage.FIELD_BODY, msg.getBody());
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        String n = from;

        if (n.contains(" ")) {
            String[] nn = n.split(" ");
            n = nn[0];
        }

        messageNotification.setContentTitle(n);
        if (msg.getBody().toString().contains(imagefile)) {
            String[] arr = msg.getBody().toString().trim().split("@@");
            arr = arr[1].split("-");
            if (arr[0].equals("VID")) {
                messageNotification.setTicker("Sent a video");
            } else if (arr[0].equals("AUD")) {
                messageNotification.setTicker("Sent an audio");
            } else if (arr[0].equals("IMG")) {
                messageNotification.setTicker("Sent an image");
            } else if (arr[0].equals("CON")) {
                messageNotification.setTicker("Sent a contact");
            } else if (arr[0].equals("LOC")) {
                messageNotification.setTicker("Sent a location");
            }
        } else {
            messageNotification.setContentText(msg.getBody());
        }
        messageNotification.setContentIntent(contentIntent);

        System.out.println("messageNotification.build() ==" + messageNotification.build() + "");

        if (!msg.getFrom().equals("sip:registrar@kamailio.org")
                && !msg.getBody().contains("[Offline message -")) {
            notificationManager.notify(MESSAGE_NOTIF_ID, messageNotification.build());
        }
    }
}

From source file:com.kaku.weac.fragment.AlarmClockOntimeFragment.java

/**
 * ??/* w  ww.ja va  2s  .c o m*/
 */
@TargetApi(19)
private void nap() {
    // ??X
    if (mNapTimesRan == mNapTimes) {
        return;
    }
    // ??1
    mNapTimesRan++;
    LogUtil.d(LOG_TAG, "??" + mNapTimesRan);

    // ???
    Intent intent = new Intent(getActivity(), AlarmClockBroadcast.class);
    intent.putExtra(WeacConstants.ALARM_CLOCK, mAlarmClock);
    intent.putExtra(WeacConstants.NAP_RAN_TIMES, mNapTimesRan);
    PendingIntent pi = PendingIntent.getBroadcast(getActivity(), -mAlarmClock.getId(), intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Activity.ALARM_SERVICE);
    // XXX
    // ?
    long nextTime = System.currentTimeMillis() + 1000 * 60 * mNapInterval;

    LogUtil.i(LOG_TAG, "??:" + mNapInterval + "");

    // ?194.4
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, nextTime, pi);
    } else {
        alarmManager.set(AlarmManager.RTC_WAKEUP, nextTime, pi);
    }

    // ?
    Intent it = new Intent(getActivity(), AlarmClockNapNotificationActivity.class);
    it.putExtra(WeacConstants.ALARM_CLOCK, mAlarmClock);
    // FLAG_UPDATE_CURRENT ???
    // FLAG_ONE_SHOT ??
    PendingIntent napCancel = PendingIntent.getActivity(getActivity(), mAlarmClock.getId(), it,
            PendingIntent.FLAG_CANCEL_CURRENT);
    // 
    CharSequence time = new SimpleDateFormat("HH:mm", Locale.getDefault()).format(nextTime);

    // 
    NotificationCompat.Builder builder = new NotificationCompat.Builder(getActivity());
    // PendingIntent
    Notification notification = builder.setContentIntent(napCancel)
            // ?
            .setDeleteIntent(napCancel)
            // 
            .setContentTitle(String.format(getString(R.string.xx_naping), mAlarmClock.getTag()))
            // 
            .setContentText(String.format(getString(R.string.nap_to), time))
            // ???
            .setTicker(String.format(getString(R.string.nap_time), mNapInterval))
            // ???
            .setSmallIcon(R.drawable.ic_nap_notification)
            // 
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
            .setAutoCancel(true)
            // ??
            .setDefaults(NotificationCompat.DEFAULT_LIGHTS | NotificationCompat.FLAG_SHOW_LIGHTS).build();
    /*        notification.defaults |= Notification.DEFAULT_LIGHTS;
            notification.flags |= Notification.FLAG_SHOW_LIGHTS;*/

    // ???
    mNotificationManager.notify(mAlarmClock.getId(), notification);
}

From source file:com.newcell.calltext.service.SipNotifications.java

public void showNotificationForVoiceMail(SipProfile acc, int numberOfMessages) {
    if (messageVoicemail == null) {

        messageVoicemail = new NotificationCompat.Builder(context);
        messageVoicemail.setSmallIcon(android.R.drawable.stat_notify_voicemail);
        messageVoicemail.setTicker(context.getString(R.string.voice_mail));
        messageVoicemail.setWhen(System.currentTimeMillis());
        messageVoicemail.setDefaults(Notification.DEFAULT_ALL);
        messageVoicemail.setAutoCancel(true);
        messageVoicemail.setOnlyAlertOnce(true);
    }/* www . ja va 2  s . c om*/

    PendingIntent contentIntent = null;
    Intent notificationIntent;
    /*
     * 8/06/2014 Removed check for voicemail number. Changed it to call *86
             
    if (acc != null && !TextUtils.isEmpty(acc.vm_nbr) && acc.vm_nbr != "null") {
    notificationIntent = new Intent(Intent.ACTION_CALL);
    notificationIntent.setData(SipUri.forgeSipUri(SipManager.PROTOCOL_CSIP, acc.vm_nbr
            + "@" + acc.getDefaultDomain()));
    notificationIntent.putExtra(SipProfile.FIELD_ACC_ID, acc.id);
    }
            
     * 
     */
    if (acc != null) {
        notificationIntent = new Intent(Intent.ACTION_CALL);
        notificationIntent.setData(SipUri.forgeSipUri(SipManager.PROTOCOL_CSIP, "*86"));
        notificationIntent.putExtra(SipProfile.FIELD_ACC_ID, acc.id);
    } else {
        notificationIntent = new Intent(SipManager.ACTION_SIP_DIALER);
    }
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    String messageText = "";
    /*
     * 6/11/2014 Removed account name from voicemail notification
             
    if (acc != null) {
    messageText += acc.getProfileName() + " : ";
    }
            
     * 6/11/2014 Removed account name from voicemail notification
     */
    messageText = Integer.toString(numberOfMessages);
    messageText += " new " + context.getString(R.string.voice_mail);
    if (numberOfMessages > 1)
        messageText += "s";

    messageVoicemail.setContentTitle(context.getString(R.string.voice_mail));
    messageVoicemail.setContentText(messageText);
    if (contentIntent != null) {
        messageVoicemail.setContentIntent(contentIntent);
        notificationManager.notify(VOICEMAIL_NOTIF_ID, messageVoicemail.build());
    }
}

From source file:org.adblockplus.android.AdblockPlus.java

/**
 * Sets Alarm to call updater after specified number of minutes or after one
 * day if//from  w w  w .  jav a2s.  c  o  m
 * minutes are set to 0.
 * 
 * @param minutes
 *          number of minutes to wait
 */
public void scheduleUpdater(int minutes) {
    Calendar updateTime = Calendar.getInstance();

    if (minutes == 0) {
        // Start update checks at 10:00 GMT...
        updateTime.setTimeZone(TimeZone.getTimeZone("GMT"));
        updateTime.set(Calendar.HOUR_OF_DAY, 10);
        updateTime.set(Calendar.MINUTE, 0);
        // ...next day
        updateTime.add(Calendar.HOUR_OF_DAY, 24);
        // Spread out the mass downloading? for 6 hours
        updateTime.add(Calendar.MINUTE, (int) (Math.random() * 60 * 6));
    } else {
        updateTime.add(Calendar.MINUTE, minutes);
    }

    Intent updater = new Intent(this, AlarmReceiver.class);
    PendingIntent recurringUpdate = PendingIntent.getBroadcast(this, 0, updater,
            PendingIntent.FLAG_CANCEL_CURRENT);
    // Set non-waking alarm
    AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarms.set(AlarmManager.RTC, updateTime.getTimeInMillis(), recurringUpdate);
}

From source file:com.mobilyzer.MeasurementScheduler.java

private synchronized void handleMeasurement() {
    alarmManager.cancel(measurementIntentSender);
    setCurrentTask(null);/*from w  ww. java  2 s .  c  o  m*/
    try {
        Logger.d("MeasurementScheduler -> In handleMeasurement " + mainQueue.size() + " "
                + waitingTasksQueue.size());
        MeasurementTask task = mainQueue.peek();
        // update the waiting queue. It contains all the tasks that are ready
        // to be executed. Here we extract all those ready tasks from main queue
        while (task != null && task.timeFromExecution() <= 0) {
            mainQueue.poll();

            if (task.getDescription().getType().equals(RRCTask.TYPE)
                    && phoneUtils.getNetwork().equals(PhoneUtils.NETWORK_WIFI)) {
                long updatedStartTime = System.currentTimeMillis() + (long) (10 * 60 * 1000);
                task.getDescription().startTime.setTime(updatedStartTime);
                mainQueue.add(task);
                Logger.i("MeasurementScheduler: handleMeasurement: delaying RRC task on "
                        + phoneUtils.getNetwork());
                task = mainQueue.peek();
                continue;
            }
            Logger.i("MeasurementScheduler: handleMeasurement: " + task.getDescription().key + " "
                    + task.getDescription().type + " added to waiting list");
            waitingTasksQueue.add(task);
            task = mainQueue.peek();
        }

        if (!phoneUtils.isNetworkAvailable()) {
            Logger.i("No connection is available, set an alarm for 5 min");
            measurementIntentSender = PendingIntent.getBroadcast(this, 0,
                    new UpdateIntent(UpdateIntent.MEASUREMENT_ACTION), PendingIntent.FLAG_CANCEL_CURRENT);
            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 60 * 1000),
                    measurementIntentSender);
            return;
        }

        if (waitingTasksQueue.size() != 0) {
            Logger.i("waiting list size is " + waitingTasksQueue.size());
            MeasurementTask ready = waitingTasksQueue.poll();
            Logger.i("ready: " + ready.getDescription().getType());

            MeasurementDesc desc = ready.getDescription();
            long newStartTime = desc.startTime.getTime() + (long) desc.intervalSec * 1000;

            if (desc.count == MeasurementTask.INFINITE_COUNT
                    && desc.priority != MeasurementTask.USER_PRIORITY) {
                if (serverTasks.containsKey(desc.toString())
                        && serverTasks.get(desc.toString()).after(desc.endTime)) {
                    ready.getDescription().endTime.setTime(serverTasks.get(desc.toString()).getTime());
                }
            }

            /**
             * Add a clone of the task if it's still valid it does not change the taskID (hashCode)
             */
            if (newStartTime < ready.getDescription().endTime.getTime()
                    && (desc.count == MeasurementTask.INFINITE_COUNT || desc.count > 1)) {
                MeasurementTask newTask = ready.clone();
                if (desc.count != MeasurementTask.INFINITE_COUNT) {
                    newTask.getDescription().count--;
                }
                newTask.getDescription().startTime.setTime(newStartTime);
                tasksStatus.put(newTask.getTaskId(), TaskStatus.SCHEDULED);
                mainQueue.add(newTask);
            } else {
                if (desc.priority != MeasurementTask.USER_PRIORITY) {
                    serverTasks.remove(desc.toString());
                }
            }

            if (ready.getDescription().endTime.before(new Date())) {
                Intent intent = new Intent();
                intent.setAction(UpdateIntent.MEASUREMENT_PROGRESS_UPDATE_ACTION);
                intent.putExtra(UpdateIntent.TASK_STATUS_PAYLOAD, Config.TASK_CANCELED);
                MeasurementResult[] tempResults = MeasurementResult.getFailureResult(ready,
                        new CancellationException("Task cancelled!"));
                intent.putExtra(UpdateIntent.RESULT_PAYLOAD, tempResults);
                intent.putExtra(UpdateIntent.TASKID_PAYLOAD, ready.getTaskId());
                intent.putExtra(UpdateIntent.CLIENTKEY_PAYLOAD, ready.getKey());
                MeasurementScheduler.this.sendBroadcast(intent);

                if (desc.priority != MeasurementTask.USER_PRIORITY) {
                    serverTasks.remove(desc.toString());
                }

                handleMeasurement();
            } else {
                Logger.d("MeasurementScheduler -> " + ready.getDescription().getType() + " is gonna run");
                Future<MeasurementResult[]> future;
                setCurrentTask(ready);
                setCurrentTaskStartTime(Calendar.getInstance().getTime());
                if (ready.getDescription().priority == MeasurementTask.USER_PRIORITY) {
                    // User task can override the power policy. So a different task wrapper is used.
                    future = measurementExecutor.submit(new UserMeasurementTask(ready, this));
                } else {
                    future = measurementExecutor
                            .submit(new ServerMeasurementTask(ready, this, resourceCapManager));
                }

                synchronized (pendingTasks) {
                    pendingTasks.put(ready, future);
                }
            }
        } else {// if(task.timeFromExecution()>0){
            MeasurementTask waiting = mainQueue.peek();
            if (waiting != null) {
                long timeFromExecution = task.timeFromExecution();
                measurementIntentSender = PendingIntent.getBroadcast(this, 0,
                        new UpdateIntent(UpdateIntent.MEASUREMENT_ACTION), PendingIntent.FLAG_CANCEL_CURRENT);
                alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeFromExecution,
                        measurementIntentSender);
                setCurrentTask(null);// TODO
                setCurrentTaskStartTime(null);
            }

        }
    } catch (IllegalArgumentException e) {
        // Task creation in clone can create this exception

    } catch (Exception e) {
        // We don't want any unexpected exception to crash the process
    }
}