Example usage for android.app AlarmManager RTC_WAKEUP

List of usage examples for android.app AlarmManager RTC_WAKEUP

Introduction

In this page you can find the example usage for android.app AlarmManager RTC_WAKEUP.

Prototype

int RTC_WAKEUP

To view the source code for android.app AlarmManager RTC_WAKEUP.

Click Source Link

Document

Alarm time in System#currentTimeMillis System.currentTimeMillis() (wall clock time in UTC), which will wake up the device when it goes off.

Usage

From source file:com.remdo.app.MainActivity.java

/**
 * Enables Alerts service with configured minutes span in Services database
 *///  w  w w  .jav a2 s.  c o m
private void enableNotificationsService() {
    mAlertsInterval = dm.getServcieMinutes("Alerts");
    long milisegundos = mAlertsInterval * 60 * 1000;

    Intent intent = new Intent(this, NotificationService.class);
    pendingAlertsIntent = PendingIntent.getService(this, 0, intent, 0);

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.add(Calendar.SECOND, 10);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), milisegundos,
            pendingAlertsIntent);

    Toast.makeText(this, getString(R.string.started_alerts_service), Toast.LENGTH_LONG).show();
}

From source file:com.sean.takeastand.storage.ScheduleEditor.java

private void setDailyRepeatingAlarm(int UID, String time) {
    Intent intent = new Intent(mContext, StartScheduleReceiver.class);
    intent.putExtra(Constants.ALARM_UID, UID);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, UID, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    ((AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE)).setRepeating(AlarmManager.RTC_WAKEUP,
            nextAlarmTime(time).getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
    Log.i(TAG, "Set Daily Repeating alarm for " + Long.toString(nextAlarmTime(time).getTimeInMillis())
            + " current time " + Long.toString(System.currentTimeMillis()));
}

From source file:com.atlas.mars.weatherradar.MainActivity.java

void alarmOn() {
    am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    intent1 = createIntent("action 1", "extra 1", SampleBootReceiver.class);
    pIntent1 = PendingIntent.getBroadcast(this, 0, intent1, PendingIntent.FLAG_CANCEL_CURRENT);
    am.cancel(pIntent1);//from w  ww. j  a  v a  2s  . com

    //todo ??
    //am.set(AlarmManager.RTC_WAKEUP, startAlarm, pIntent1);
    am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1 * 1000, pIntent1);
}

From source file:com.nextgis.firereporter.GetFiresService.java

protected void ScheduleNextUpdate(Context context, int nCommand, long nMinTimeBetweenSend,
        boolean bEnergyEconomy) {
    if (context == null)
        return;// w  ww.  j a  v  a2s . c o  m

    Intent intent = new Intent(MainActivity.INTENT_NAME);
    intent.putExtra(RECEIVER, mUserNasaReceiver);
    intent.putExtra(RECEIVER_SCANEX, mScanexReceiver);
    intent.putExtra(COMMAND, nCommand);
    intent.putExtra(SOURCE, mnFilter);

    PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // The update frequency should often be user configurable.  This is not.

    long currentTimeMillis = System.currentTimeMillis();
    long nextUpdateTimeMillis = currentTimeMillis + nMinTimeBetweenSend;
    Time nextUpdateTime = new Time();
    nextUpdateTime.set(nextUpdateTimeMillis);

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    if (bEnergyEconomy)
        alarmManager.set(AlarmManager.RTC, nextUpdateTimeMillis, pendingIntent);
    else
        alarmManager.set(AlarmManager.RTC_WAKEUP, nextUpdateTimeMillis, pendingIntent);
}

From source file:com.battlelancer.seriesguide.service.NotificationService.java

@SuppressLint("CommitPrefEdits")
@TargetApi(android.os.Build.VERSION_CODES.KITKAT)
@Override//  ww  w.j  a v  a  2 s .  c o m
protected void onHandleIntent(Intent intent) {
    Timber.d("Waking up...");
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    /*
     * Handle a possible delete intent.
     */
    if (handleDeleteIntent(this, intent)) {
        return;
    }

    /*
     * Unschedule notification service wake-ups for disabled notifications
     * and non-supporters.
     */
    if (!NotificationSettings.isNotificationsEnabled(this) || !Utils.hasAccessToX(this)) {
        Timber.d("Notification service disabled, removing wakup-up alarm");
        // cancel any pending alarm
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(this, OnAlarmReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
        am.cancel(pi);

        resetLastEpisodeAirtime(prefs);

        return;
    }

    long wakeUpTime = 0;

    /*
     * Get pool of episodes which air from 12 hours ago until eternity which
     * match the users settings.
     */
    StringBuilder selection = new StringBuilder(SELECTION);
    boolean isFavsOnly = NotificationSettings.isNotifyAboutFavoritesOnly(this);
    Timber.d("Do notify about " + (isFavsOnly ? "favorites ONLY" : "ALL"));
    if (isFavsOnly) {
        selection.append(" AND ").append(Shows.SELECTION_FAVORITES);
    }
    boolean isNoSpecials = DisplaySettings.isHidingSpecials(this);
    Timber.d("Do " + (isNoSpecials ? "NOT " : "") + "notify about specials");
    if (isNoSpecials) {
        selection.append(" AND ").append(Episodes.SELECTION_NO_SPECIALS);
    }
    // always exclude hidden shows
    selection.append(" AND ").append(Shows.SELECTION_NO_HIDDEN);

    final long customCurrentTime = TimeTools.getCurrentTime(this);
    final Cursor upcomingEpisodes = getContentResolver().query(Episodes.CONTENT_URI_WITHSHOW, PROJECTION,
            selection.toString(),
            new String[] { String.valueOf(customCurrentTime - 12 * DateUtils.HOUR_IN_MILLIS) }, SORTING);

    if (upcomingEpisodes != null) {
        int notificationThreshold = NotificationSettings.getLatestToIncludeTreshold(this);
        if (DEBUG) {
            Timber.d("DEBUG MODE: notification threshold is 1 week");
            // a week, for debugging (use only one show to get single
            // episode notifications)
            notificationThreshold = 10080;
            // notify again for same episodes
            resetLastEpisodeAirtime(prefs);
        }

        final long nextEpisodeReleaseTime = NotificationSettings.getNextToNotifyAbout(this);
        // wake user-defined amount of time earlier than next episode release time
        final long plannedWakeUpTime = TimeTools.getEpisodeReleaseTime(this, nextEpisodeReleaseTime).getTime()
                - DateUtils.MINUTE_IN_MILLIS * notificationThreshold;

        /*
         * Set to -1 as on first run nextTimePlanned will be 0. This assures
         * we still see notifications of upcoming episodes then.
         */
        int newEpisodesAvailable = -1;

        // Check if we did wake up earlier than planned
        if (System.currentTimeMillis() < plannedWakeUpTime) {
            Timber.d("Woke up earlier than planned, checking for new episodes");
            newEpisodesAvailable = 0;
            long latestTimeNotified = NotificationSettings.getLastNotified(this);

            // Check if there are any earlier episodes to notify about
            while (upcomingEpisodes.moveToNext()) {
                final long releaseTime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS);
                if (releaseTime < nextEpisodeReleaseTime) {
                    if (releaseTime > latestTimeNotified) {
                        /**
                         * This will not get new episodes which would have
                         * aired the same time as the last one we notified
                         * about. Sad, but the best we can do right now.
                         */
                        newEpisodesAvailable = 1;
                        break;
                    }
                } else {
                    break;
                }
            }
        }

        if (newEpisodesAvailable == 0) {
            // Go to sleep, wake up as planned
            Timber.d("No new episodes, going to sleep.");
            wakeUpTime = plannedWakeUpTime;
        } else {
            // Get episodes which are within the notification threshold
            // (user set) and not yet cleared
            final List<Integer> notifyPositions = new ArrayList<>();
            final long latestTimeCleared = NotificationSettings.getLastCleared(this);
            final long latestTimeToInclude = customCurrentTime
                    + DateUtils.MINUTE_IN_MILLIS * notificationThreshold;

            int position = -1;
            upcomingEpisodes.moveToPosition(position);
            while (upcomingEpisodes.moveToNext()) {
                position++;

                final long releaseTime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS);
                if (releaseTime <= latestTimeToInclude) {
                    /*
                     * Only add those after the last one the user cleared.
                     * At most those of the last 24 hours (see query above).
                     */
                    if (releaseTime > latestTimeCleared) {
                        notifyPositions.add(position);
                    }
                } else {
                    // Too far into the future, stop!
                    break;
                }
            }

            // Notify if we found any episodes
            if (notifyPositions.size() > 0) {
                // store latest air time of all episodes we notified about
                upcomingEpisodes.moveToPosition(notifyPositions.get(notifyPositions.size() - 1));
                long latestAirtime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS);
                if (!AndroidUtils.isHoneycombOrHigher()) {
                    /*
                     * Everything below HC does not have delete intents, so
                     * we just never notify about the same episode twice.
                     */
                    Timber.d("Delete intent NOT supported, setting last cleared to: " + latestAirtime);
                    prefs.edit().putLong(NotificationSettings.KEY_LAST_CLEARED, latestAirtime).commit();
                }
                Timber.d("Found " + notifyPositions.size() + " new episodes, setting last notified to: "
                        + latestAirtime);
                prefs.edit().putLong(NotificationSettings.KEY_LAST_NOTIFIED, latestAirtime).commit();

                onNotify(upcomingEpisodes, notifyPositions, latestAirtime);
            }

            /*
             * Plan next episode to notify about, calc wake-up alarm as
             * early as user wants.
             */
            upcomingEpisodes.moveToPosition(-1);
            while (upcomingEpisodes.moveToNext()) {
                final long releaseTime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS);
                if (releaseTime > latestTimeToInclude) {
                    // store next episode we plan to notify about
                    Timber.d("Storing next episode time to notify about: " + releaseTime);
                    prefs.edit().putLong(NotificationSettings.KEY_NEXT_TO_NOTIFY, releaseTime).commit();

                    // calc actual wake up time
                    wakeUpTime = TimeTools.getEpisodeReleaseTime(this, releaseTime).getTime()
                            - DateUtils.MINUTE_IN_MILLIS * notificationThreshold;

                    break;
                }
            }
        }

        upcomingEpisodes.close();
    }

    // Set a default wake-up time if there are no future episodes for now
    if (wakeUpTime <= 0) {
        wakeUpTime = System.currentTimeMillis() + 6 * DateUtils.HOUR_IN_MILLIS;
        Timber.d("No future episodes found, wake up in 6 hours");
    }

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(this, NotificationService.class);
    PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
    Timber.d("Going to sleep, setting wake-up alarm to: " + wakeUpTime);
    if (AndroidUtils.isKitKatOrHigher()) {
        am.setExact(AlarmManager.RTC_WAKEUP, wakeUpTime, pi);
    } else {
        am.set(AlarmManager.RTC_WAKEUP, wakeUpTime, pi);
    }
}

From source file:com.michael.feng.textlater.NewActivity.java

private void scheduleTask(Message message) {

    Calendar calendar = Calendar.getInstance();
    if (null != whenMap && whenMap.containsKey("year")) {
        calendar.set(Calendar.YEAR, whenMap.get("year"));
        calendar.set(Calendar.MONTH, whenMap.get("month"));
        calendar.set(Calendar.DAY_OF_MONTH, whenMap.get("day"));
        calendar.set(Calendar.HOUR_OF_DAY, whenMap.get("hour"));
        calendar.set(Calendar.MINUTE, whenMap.get("min"));
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        cleanWhenMap();// ww  w  .  jav  a  2 s . c o  m
    }

    Intent intent = new Intent(this, AlarmReceiver.class);
    intent.putExtra("textContact", message.getTextContact().trim());
    intent.putExtra("textNumber", message.getTextNumber().trim());
    intent.putExtra("textWhen", message.getTextWhen());
    intent.putExtra("textContent", message.getTextContent());
    // Different requestCode can lead to different PendingIntent
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, (int) calendar.getTimeInMillis(), intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);

    Log.d("requstcode in new-->", calendar.getTimeInMillis() + "");

    // AlarmManager.RTC_WAKEUP can be executed when CPU sleep
    // AlarmManager.RTC can't be executed when CPU sleep
    am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}

From source file:com.kyleszombathy.sms_scheduler.MessageAlarmReceiver.java

/** Method to set a new alarm
 * @param context The app context/*from ww  w.j  av  a  2s  .  com*/
 * @param timeToSend The Time to send the message (in Calendar format)
 * @param phoneNumberList String Arraylist of phone numbers
 * @param messageContent The content of the message you want to send
 * @param alarmNumber Provide an identifier for the alarm
 * @param nameList The list of names, corresponding with the phone numbers*/
public void createAlarm(Context context, Calendar timeToSend, ArrayList<String> phoneNumberList,
        String messageContent, int alarmNumber, ArrayList<String> nameList) {
    this.context = context;

    // Creates new alarm
    alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intentAlarm = new Intent(context, MessageAlarmReceiver.class);

    // Add extras
    Bundle extras = new Bundle();
    extras.putStringArrayList("pNum", phoneNumberList);
    extras.putString("message", messageContent);
    extras.putInt("alarmNumber", alarmNumber);
    extras.putStringArrayList("nameList", nameList);
    intentAlarm.putExtras(extras);

    // Set alarm
    pendingIntent = PendingIntent.getBroadcast(context, alarmNumber, intentAlarm,
            PendingIntent.FLAG_UPDATE_CURRENT);
    alarm.set(AlarmManager.RTC_WAKEUP, timeToSend.getTimeInMillis(), pendingIntent);

    // Enable {@code MessageBootReceiver} to automatically restart the alarm when the
    // device is rebooted.
    ComponentName receiver = new ComponentName(context, MessageBootReceiver.class);
    PackageManager pm = context.getPackageManager();

    pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);

    Log.i(TAG, "createAlarm: Alarm Created. alarmNumber: " + alarmNumber);
}

From source file:com.intel.RtcPingDownloadTester.java

private void setAlarm(long millis) {
    Intent intent = new Intent(ACTION_NAME);
    pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    Log.v(TAG, "setAlarm millis = " + millis);
    if (millis == 0)
        return;/*from  w w w.ja v a 2 s.  c  o m*/
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + millis, pendingIntent);
    return;
}

From source file:com.snda.mymarket.providers.downloads.DownloadService.java

/**
 * Update {@link #mDownloads} to match {@link DownloadProvider} state.
 * Depending on current download state it may enqueue {@link DownloadThread}
 * instances, request {@link DownloadScanner} scans, update user-visible
 * notifications, and/or schedule future actions with {@link AlarmManager}.
 * <p>//w w w .j  ava  2s  . c om
 * Should only be called from {@link #mUpdateThread} as after being
 * requested through {@link #enqueueUpdate()}.
 * 
 * @return If there are active tasks being processed, as of the database
 *         snapshot taken in this update.
 */
private boolean updateLocked() {
    final long now = mSystemFacade.currentTimeMillis();
    boolean isActive = false;
    long nextActionMillis = Long.MAX_VALUE;
    final Set<Long> staleIds = new HashSet<Long>(mDownloads.size());
    final ContentResolver resolver = getContentResolver();
    final Cursor cursor = resolver.query(Downloads.ALL_DOWNLOADS_CONTENT_URI, null, null, null, null);
    try {
        final DownloadInfo.Reader reader = new DownloadInfo.Reader(resolver, cursor);
        final int idColumn = cursor.getColumnIndexOrThrow(Downloads._ID);
        while (cursor.moveToNext()) {
            final long id = cursor.getLong(idColumn);
            staleIds.remove(id);
            DownloadInfo info = mDownloads.get(id);
            if (info != null) {
                updateDownload(reader, info, now);
            } else {
                info = insertDownloadLocked(reader, now);
            }
            if (info.mDeleted) {
                // Delete download if requested, but only after cleaning up
                if (!TextUtils.isEmpty(info.mMediaProviderUri)) {
                    resolver.delete(Uri.parse(info.mMediaProviderUri), null, null);
                }
                Helpers.deleteFile(getContentResolver(), info.mId, info.mFileName, info.mMimeType);
            } else {
                // Kick off download task if ready
                final boolean activeDownload = info.startIfReady(this.mNotifier);
                final boolean activeScan = info.startScanIfReady(mScanner);
                if (DEBUG_LIFECYCLE && (activeDownload || activeScan)) {
                    Log.v(Constants.TAG, "Download " + info.mId + ": activeDownload=" + activeDownload
                            + ", activeScan=" + activeScan);
                }
                isActive |= activeDownload;
                isActive |= activeScan;
            }
            // Keep track of nearest next action
            nextActionMillis = Math.min(info.nextActionMillis(now), nextActionMillis);
        }
    } finally {
        cursor.close();
    }
    // Clean up stale downloads that disappeared
    for (Long id : staleIds) {
        deleteDownloadLocked(id);
    }
    // Update notifications visible to user
    mNotifier.updateWith(mDownloads);
    // Set alarm when next action is in future. It's okay if the service
    // continues to run in meantime, since it will kick off an update pass.
    if (nextActionMillis > 0 && nextActionMillis < Long.MAX_VALUE) {
        if (Constants.LOGV) {
            Log.v(Constants.TAG, "scheduling start in " + nextActionMillis + "ms");
        }
        final Intent intent = new Intent(Constants.ACTION_RETRY);
        intent.setClass(this, DownloadReceiver.class);
        mAlarmManager.set(AlarmManager.RTC_WAKEUP, now + nextActionMillis,
                PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_ONE_SHOT));
    }
    return isActive;
}

From source file:org.mariotaku.twidere.service.RefreshService.java

private void rescheduleDirectMessagesRefreshing() {
    mAlarmManager.cancel(mPendingRefreshDirectMessagesIntent);
    final long refreshInterval = getRefreshInterval();
    if (refreshInterval > 0) {
        mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + refreshInterval,
                refreshInterval, mPendingRefreshDirectMessagesIntent);
    }// w  ww  .ja va  2  s  . com
}