Example usage for android.app AlarmManager setRepeating

List of usage examples for android.app AlarmManager setRepeating

Introduction

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

Prototype

public void setRepeating(@AlarmType int type, long triggerAtMillis, long intervalMillis,
        PendingIntent operation) 

Source Link

Document

Schedule a repeating alarm.

Usage

From source file:com.example.android.repeatingalarm.RepeatingAlarmFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.sample_action) {

        // BEGIN_INCLUDE (intent_fired_by_alarm)
        // First create an intent for the alarm to activate.
        // This code simply starts an Activity, or brings it to the front if it has already
        // been created.
        Intent intent = new Intent(getActivity(), MainActivity.class);
        intent.setAction(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        // END_INCLUDE (intent_fired_by_alarm)

        // BEGIN_INCLUDE (pending_intent_for_alarm)
        // Because the intent must be fired by a system service from outside the application,
        // it's necessary to wrap it in a PendingIntent.  Providing a different process with
        // a PendingIntent gives that other process permission to fire the intent that this
        // application has created.
        // Also, this code creates a PendingIntent to start an Activity.  To create a
        // BroadcastIntent instead, simply call getBroadcast instead of getIntent.
        PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), REQUEST_CODE, intent, 0);

        // END_INCLUDE (pending_intent_for_alarm)

        // BEGIN_INCLUDE (configure_alarm_manager)
        // There are two clock types for alarms, ELAPSED_REALTIME and RTC.
        // ELAPSED_REALTIME uses time since system boot as a reference, and RTC uses UTC (wall
        // clock) time.  This means ELAPSED_REALTIME is suited to setting an alarm according to
        // passage of time (every 15 seconds, 15 minutes, etc), since it isn't affected by
        // timezone/locale.  RTC is better suited for alarms that should be dependant on current
        // locale.

        // Both types have a WAKEUP version, which says to wake up the device if the screen is
        // off.  This is useful for situations such as alarm clocks.  Abuse of this flag is an
        // efficient way to skyrocket the uninstall rate of an application, so use with care.
        // For most situations, ELAPSED_REALTIME will suffice.
        int alarmType = AlarmManager.ELAPSED_REALTIME;
        final int FIFTEEN_SEC_MILLIS = 15000;

        // The AlarmManager, like most system services, isn't created by application code, but
        // requested from the system.
        AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(getActivity().ALARM_SERVICE);

        // setRepeating takes a start delay and period between alarms as arguments.
        // The below code fires after 15 seconds, and repeats every 15 seconds.  This is very
        // useful for demonstration purposes, but horrendous for production.  Don't be that dev.
        alarmManager.setRepeating(alarmType, SystemClock.elapsedRealtime() + FIFTEEN_SEC_MILLIS,
                FIFTEEN_SEC_MILLIS, pendingIntent);
        // END_INCLUDE (configure_alarm_manager);
        Log.i("RepeatingAlarmFragment", "Alarm set.");
    }//w  ww .j  a v a  2  s.  c o m
    return true;
}

From source file:support.plus.reportit.SettingsActivity.java

public void scheduleNotification(Notification notification, int hour, int minute) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, hour);
    calendar.set(Calendar.MINUTE, minute);

    Intent notificationIntent = new Intent(this, AlarmReceiver.class);
    notificationIntent.putExtra(AlarmReceiver.NOTIFICATION_ID, 1);
    notificationIntent.putExtra(AlarmReceiver.NOTIFICATION, notification);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
            pendingIntent);//w ww  .  ja  va2 s .  c om

}

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();//from www . j  av  a 2 s.co  m

    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.shinymetal.gradereport.AbstractActivity.java

protected void setRecurringAlarm(Context context, boolean force) {

    boolean alarmUp = (PendingIntent.getBroadcast(context, 0, new Intent(context, AlarmReceiver.class),
            PendingIntent.FLAG_NO_CREATE) != null);

    if (alarmUp && !force)
        return;// w w  w . j  ava2  s  . c o  m

    Intent downloader = new Intent(context, AlarmReceiver.class);
    downloader.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, downloader,
            PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    Date firstRun = new Date();
    long mSyncInterval = Long.parseLong(PreferenceManager.getDefaultSharedPreferences(this)
            .getString(getString(R.string.pref_sync_key), "15")) * 60000;

    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, firstRun.getTime() + 10, mSyncInterval, pendingIntent);

    if (BuildConfig.DEBUG)
        Log.d(this.toString(), TS.get() + this.toString() + " Set alarmManager.setRepeating to: "
                + firstRun.toString() + " interval: " + mSyncInterval);
}

From source file:com.robsterthelobster.ucibustracker.ArrivalsFragment.java

private void updateRouteData() {
    Intent alarmIntent = new Intent(getActivity(), UciBusIntentService.AlarmReceiver.class);

    PendingIntent pi = PendingIntent.getBroadcast(getActivity(), 0, alarmIntent, 0);

    AlarmManager am = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.add(Calendar.SECOND, 0);
    long frequency = 60 * 1000; // one minute, which is the minimum

    am.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), frequency, pi);
}

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);/*from w  w w.ja v  a 2 s.com*/
    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.xperia64.cosi.CosiActivity.java

public void scheduleAlarm() {
    if (checkAlarm()) {
        return;/*from   ww w . j  a v a 2 s.  c om*/
    }
    final int interval = 60 * 30;
    Intent alarmIntent = null;
    PendingIntent pendingIntent = null;
    AlarmManager alarmManager = null;

    // OnCreate()
    alarmIntent = new Intent(this, NagReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), NagReceiver.REQUEST_CODE,
            alarmIntent, 0);
    alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), (interval * 1000),
            pendingIntent);
}

From source file:ca.ualberta.cs.drivr.MainActivity.java

private void setNotificationAlarm(Context context) {
    Log.d("ME", "Alarm setup");
    Intent intent = new Intent(getApplicationContext(), NotificationReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

    AlarmManager am = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    am.cancel(pendingIntent);/*  w ww. j  av a 2  s .  c o m*/
    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000, pendingIntent);
    Log.d("ME", "Alarm started");
}

From source file:com.poloure.simplerss.FeedsActivity.java

private void setServiceIntent(int state) {
    // Load the ManageFeedsRefresh boolean value from settings.
    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    if (!pref.getBoolean("refreshing_enabled", false) && ALARM_SERVICE_START == state) {
        return;/* ww w  . j  a  va2 s.c o m*/
    }

    // Create intent, turn into pending intent, and get the alarm manager.
    Intent intent = new Intent(this, ServiceUpdate.class);

    PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0);
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);

    // Depending on the state string, start or stop the service.
    if (ALARM_SERVICE_START == state) {
        String intervalString = pref.getString("refresh_interval", "120");

        long interval = Long.parseLong(intervalString) * MINUTE_VALUE;
        long next = System.currentTimeMillis() + interval;
        am.setRepeating(AlarmManager.RTC_WAKEUP, next, interval, pendingIntent);
    } else if (ALARM_SERVICE_STOP == state) {
        am.cancel(pendingIntent);
    }
}

From source file:com.adguard.android.service.FilterServiceImpl.java

@Override
public void scheduleFiltersUpdate() {
    Intent alarmIntent = new Intent(AlarmReceiver.UPDATE_FILTER_ACTION);

    boolean isRunning = PendingIntent.getBroadcast(context, 0, alarmIntent,
            PendingIntent.FLAG_NO_CREATE) != null;
    if (!isRunning) {
        LOG.info("Starting scheduler of filters updating");
        PendingIntent broadcastIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, UPDATE_INITIAL_PERIOD, AlarmManager.INTERVAL_HOUR,
                broadcastIntent);//from w ww.  j  a  va2  s .co m
    } else {
        LOG.info("Filters update is running");
    }
}