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:se.erichansander.retrotimer.RetroTimer.java

/**
 * Sets an alarm at absolute time alarmTime (in millis from epoch)
 *//*from w w w.j a  v  a  2  s .c o  m*/
public static void setAlarmAt(Context context, long alarmTime) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor ed = prefs.edit();
    ed.putLong(RetroTimer.PREF_ALARM_TIME, alarmTime);
    ed.putBoolean(RetroTimer.PREF_ALARM_SET, true);
    ed.commit();

    Intent intent = new Intent(RetroTimer.ALARM_TRIGGER_ACTION);
    intent.putExtra(RetroTimer.ALARM_TIME_EXTRA, alarmTime);
    PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    /*
     * Activate alarm in AlarmManager. Since the API for activating the
     * alarm changed in KitKat, we need to treat the two versions
     * differently, and since "Dalvik in Android 1.x was very conservative
     * and would crash if you try to load a class that contains a reference
     * that it cannot resolve" we have to put it in a separate class...
     * 
     * See
     * http://stackoverflow.com/questions/13444255/could-not-find-method-
     * from-the-newer-api-with-using-targetapi-annotation
     */
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
        am.set(AlarmManager.RTC_WAKEUP, alarmTime, sender);
    } else {
        AlarmManagerKitKat.set(am, alarmTime, sender);
    }

    // Trigger a notification that, when clicked, will open TimerSet
    Intent viewAlarm = new Intent(context, TimerSet.class);
    viewAlarm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent pendingNotify = PendingIntent.getActivity(context, 0, viewAlarm, 0);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setContentIntent(pendingNotify).setDefaults(Notification.DEFAULT_LIGHTS).setOngoing(true)
            .setSmallIcon(R.drawable.ic_stat_alarm_set)
            .setContentTitle(context.getString(R.string.notify_set_label)).setContentText(context
                    .getString(R.string.notify_set_text, DateFormat.getTimeFormat(context).format(alarmTime)));

    /*
     * Send the notification using the alarm id to easily identify the
     * correct notification.
     */
    NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    nm.notify(RetroTimer.NOTIF_SET_ID, mBuilder.build());
}

From source file:ca.zadrox.dota2esportticker.service.ReminderAlarmService.java

private void scheduleAlarm(final long matchId, final long matchStart) {

    final long currentTime = TimeUtils.getUTCTime();
    LOGD(TAG, "Schedule Alarm");

    if (currentTime > matchStart) {
        LOGD(TAG, "CurrentTime > matchStart");
        return;/*from w  ww. ja v  a 2s .c  o m*/
    }

    long alarmTime = matchStart - MILLI_TEN_MINUTES;

    final Intent notifIntent = new Intent(ACTION_NOTIFY_MATCH, null, this, ReminderAlarmService.class);

    notifIntent.setData(
            new Uri.Builder().authority("ca.zadrox.dota2esportticker").path(String.valueOf(matchId)).build());

    notifIntent.putExtra(ReminderAlarmService.EXTRA_MATCH_ID, matchId);
    notifIntent.putExtra(ReminderAlarmService.EXTRA_MATCH_START, matchStart);

    PendingIntent pi = PendingIntent.getService(this, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    final AlarmManager am = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);

    am.set(AlarmManager.RTC_WAKEUP, alarmTime, pi);
}

From source file:dess15proj5.fau.cs.osr_amos.mobiletimerecording.ui.MainActivity.java

/**
 * This method is used to initialize an alarm manager for this app. If the alarm is triggered, the app will check
 * whether it has to send a notification to the user reminding him to record for today.
 *
 * methodtype initialization method//w  w  w .j  av a  2  s  .  c om
 */
private void setUpAlarmForNotifications() {
    Intent intent = new Intent(this, RecordingAlarmReceiver.class);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, AccountingNotification.ALARM_ID, intent, 0);

    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    cal.set(Calendar.HOUR_OF_DAY, 20);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
            pendingIntent);
}

From source file:com.google.android.apps.iosched.service.SessionAlarmService.java

private void scheduleAlarm(final long sessionStart, final long sessionEnd, final long alarmOffset) {

    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nm.cancel(NOTIFICATION_ID);//ww w.j av  a2s  .c om
    final long currentTime = UIUtils.getCurrentTime(this);
    // If the session is already started, do not schedule system notification.
    if (currentTime > sessionStart)
        return;

    // By default, sets alarm to go off at 10 minutes before session start time.  If alarm
    // offset is provided, alarm is set to go off by that much time from now.
    long alarmTime;
    if (alarmOffset == UNDEFINED_ALARM_OFFSET) {
        alarmTime = sessionStart - MILLI_TEN_MINUTES;
    } else {
        alarmTime = currentTime + alarmOffset;
    }

    final Intent notifIntent = new Intent(ACTION_NOTIFY_SESSION, null, this, SessionAlarmService.class);
    // Setting data to ensure intent's uniqueness for different session start times.
    notifIntent.setData(new Uri.Builder().authority("com.google.android.apps.iosched")
            .path(String.valueOf(sessionStart)).build());
    notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart);
    notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd);
    notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, alarmOffset);
    PendingIntent pi = PendingIntent.getService(this, 0, notifIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    // Schedule an alarm to be fired to notify user of added sessions are about to begin.
    am.set(AlarmManager.RTC_WAKEUP, alarmTime, pi);
}

From source file:org.croudtrip.activities.MainActivity.java

@Override
public void init(Bundle savedInstanceState) {

    // Configure Navigation Drawer
    this.disableLearningPattern();
    this.allowArrowAnimation();
    this.setBackPattern(MaterialNavigationDrawer.BACKPATTERN_BACK_TO_FIRST);
    this.setDrawerHeaderImage(R.drawable.background_drawer);

    // Get all the saved user data to display some info in the navigation drawer
    showUserInfoInNavigationDrawer();//w w w  . j a  va  2  s .  c om

    SharedPreferences prefs = getSharedPreferences(Constants.SHARED_PREF_FILE_PREFERENCES,
            Context.MODE_PRIVATE);

    // Start timer to update the user's offers all the time
    if (AccountManager.isUserLoggedIn(this)) {
        Intent alarmIntent = new Intent(this, LocationUploadTimerReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);

        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(pendingIntent);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 120 * 1000,
                pendingIntent);
    }

    // Subscribe to location updates
    LocationRequest request = LocationRequest.create() //standard GMS LocationRequest
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setInterval(10000);

    ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(this);
    Subscription locationUpdateSubscription = locationProvider.getUpdatedLocation(request)
            .subscribe(new Action1<Location>() {
                @Override
                public void call(Location location) {
                    locationUpdater.setLastLocation(location);
                }
            });

    subscriptions.add(locationUpdateSubscription);

    // GPS availability
    if (!GPSavailable()) {
        checkForGPS();
    }

    // Registration for GCM, if we are not registered yet
    if (!gcmManager.isRegistered()) {
        Subscription subscription = gcmManager.register().compose(new DefaultTransformer<Void>()).retry(3)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Timber.d("Registered at GCM.");
                    }
                }, new CrashCallback(this, "failed to register for GCM"));
        subscriptions.add(subscription);
    }

    fillNavigationDrawer();
}

From source file:com.gdgdevfest.android.apps.devfestbcn.service.SessionAlarmService.java

private void scheduleAlarm(final long sessionStart, final long sessionEnd, final long alarmOffset) {

    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nm.cancel(NOTIFICATION_ID);/*from   w  ww. jav a 2s  .  c  o  m*/
    final long currentTime = UIUtils.getCurrentTime(this);
    // If the session is already started, do not schedule system notification.
    if (currentTime > sessionStart)
        return;

    // By default, sets alarm to go off at 10 minutes before session start time.  If alarm
    // offset is provided, alarm is set to go off by that much time from now.
    long alarmTime;
    if (alarmOffset == UNDEFINED_ALARM_OFFSET) {
        alarmTime = sessionStart - MILLI_TEN_MINUTES;
    } else {
        alarmTime = currentTime + alarmOffset;
    }

    final Intent notifIntent = new Intent(ACTION_NOTIFY_SESSION, null, this, SessionAlarmService.class);
    // Setting data to ensure intent's uniqueness for different session start times.
    notifIntent.setData(new Uri.Builder().authority("com.gdgdevfest.android.apps.devfestbcn")
            .path(String.valueOf(sessionStart)).build());
    notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart);
    notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd);
    notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, alarmOffset);
    PendingIntent pi = PendingIntent.getService(this, 0, notifIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    // Schedule an alarm to be fired to notify user of added sessions are about to begin.
    am.set(AlarmManager.RTC_WAKEUP, alarmTime, pi);
}

From source file:org.hansel.myAlert.AlarmFragment.java

private void setAlarm() {
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.MINUTE, Util.getPanicDelay(getActivity().getApplicationContext()));
    alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
            Util.getPendingAlarmPanicButton(getActivity().getApplicationContext()));

}

From source file:de.incoherent.suseconferenceclient.tasks.CheckForUpdatesTask.java

@Override
protected Long doInBackground(Void... params) {
    String kUrl = "https://conference.opensuse.org/osem/api/v1/conferences/gRNyOIsTbvCfJY5ENYovBA";
    if (kUrl.length() <= 0)
        return 0l;

    String updatesUrl = mConference.getUrl() + "/updates.json";
    int lastUpdateRevision = mDb.getLastUpdateValue(mConference.getSqlId());
    int revisionLevel = lastUpdateRevision;

    try {/*from  w w w.  ja va 2s  . c om*/
        JSONObject updateReply = HTTPWrapper.get(updatesUrl);
        if (updateReply == null)
            return 0l;
        int newLevel = updateReply.getInt("revision");
        if (newLevel > revisionLevel) {
            long id = mConference.getSqlId();
            // Cache favorites and alerts
            List<String> favoriteGuids = mDb.getFavoriteGuids(id);
            List<Event> alerts = mDb.getAlertEvents(id);
            List<String> alertGuids = new ArrayList<String>();
            // Now cancel all of the outstanding alerts, in case
            // a talk has been moved
            AlarmManager manager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
            for (Event e : alerts) {
                alertGuids.add("\"" + e.getGuid() + "\"");
                Log.d("SUSEConferences", "Removing an alert for " + e.getTitle());

                Intent intent = new Intent(mContext, AlarmReceiver.class);
                intent.putExtras(ScheduleDetailsActivity.generateAlarmIntentBundle(mContext, e));
                PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext,
                        intent.getStringExtra("intentId").hashCode(), intent,
                        PendingIntent.FLAG_UPDATE_CURRENT);
                manager.cancel(pendingIntent);
                pendingIntent.cancel();
            }

            // Now clear the DB
            mDb.clearDatabase(id);
            // Download schedule
            ConferenceCacher cacher = new ConferenceCacher(new ConferenceCacherProgressListener() {
                @Override
                public void progress(String progress) {
                    publishProgress(progress);
                }
            });

            long val = cacher.cacheConference(mConference, mDb);
            mErrorMessage = cacher.getLastError();
            if (val == -1) {
                mDb.setConferenceAsCached(id, 0);
            } else {
                mDb.setLastUpdateValue(id, newLevel);
                mDb.toggleEventsInMySchedule(favoriteGuids);
                mDb.toggleEventAlerts(alertGuids);
                alerts = mDb.getAlertEvents(id);
                // ... And re-create the alerts, if they are in the future
                Date currentDate = new Date();
                for (Event e : alerts) {
                    if (currentDate.after(e.getDate()))
                        continue;
                    Log.d("SUSEConferences", "Adding an alert for " + e.getTitle());
                    alertGuids.add("\"" + e.getGuid() + "\"");
                    Intent intent = new Intent(mContext, AlarmReceiver.class);
                    intent.putExtras(ScheduleDetailsActivity.generateAlarmIntentBundle(mContext, e));
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext,
                            intent.getStringExtra("intentId").hashCode(), intent,
                            PendingIntent.FLAG_UPDATE_CURRENT);
                    manager.set(AlarmManager.RTC_WAKEUP, e.getDate().getTime() - 300000, pendingIntent);
                }

            }
            return val;
        } else {
            return 0l;
        }
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:org.svij.taskwarriorapp.activities.TasksActivity.java

@Override
protected void onResume() {
    super.onResume();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    long date_long = prefs.getLong("notifications_alarm_time", System.currentTimeMillis());

    Intent myIntent = new Intent(this, NotificationService.class);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(date_long);

    alarmManager.cancel(pendingIntent);//w ww .  j  a va  2 s.c om
    if (!calendar.getTime().before(new Date())) {
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24 * 60 * 60 * 1000,
                pendingIntent);
    }
    setTitle(column + " (" + taskListFragment.getListView().getCount() + ")");
}

From source file:com.concentricsky.android.khanacademy.app.HomeActivity.java

private void setupRepeatingLibraryUpdateAlarm() {
    Log.d(LOG_TAG, "setupRepeatingLibraryUpdateAlarm");
    AlarmManager am = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);

    Intent intent = new Intent(getApplicationContext(), KADataService.class);
    intent.setAction(ACTION_LIBRARY_UPDATE);
    PendingIntent existing = PendingIntent.getService(getApplicationContext(),
            REQUEST_CODE_RECURRING_LIBRARY_UPDATE, intent, PendingIntent.FLAG_NO_CREATE);
    boolean alreadyScheduled = existing != null;

    if (!alreadyScheduled) {
        // Initial delay.
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, UPDATE_DELAY_FROM_FIRST_RUN);

        // Schedule the alarm.
        PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(),
                REQUEST_CODE_RECURRING_LIBRARY_UPDATE, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        Log.d(LOG_TAG, "(re)setting alarm");
        am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
                pendingIntent);/*from  w  ww .  j  a va  2 s.  co m*/
    }
}