Example usage for android.app AlarmManager setInexactRepeating

List of usage examples for android.app AlarmManager setInexactRepeating

Introduction

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

Prototype

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

Source Link

Document

Schedule a repeating alarm that has inexact trigger time requirements; for example, an alarm that repeats every hour, but not necessarily at the top of every hour.

Usage

From source file:app.jorge.mobile.com.transportalert.ScrollingActivity.java

public void scheduleAlarm() {
    // Construct an intent that will execute the AlarmReceiver
    Intent intent = new Intent(getApplicationContext(), MyAlarmReceiver.class);
    // Create a PendingIntent to be triggered when the alarm goes off
    final PendingIntent pIntent = PendingIntent.getBroadcast(this, MyAlarmReceiver.REQUEST_CODE, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    // Setup periodic alarm every 5 seconds
    long firstMillis = System.currentTimeMillis(); // alarm is set right away
    AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    // First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
    // Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY

    //alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
    //      AlarmManager.INTERVAL_HALF_HOUR, pIntent);

    alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis, AlarmManager.INTERVAL_HALF_HOUR, pIntent);
}

From source file:com.example.cody.tapwater.activities.MainActivity.java

@Override
public void onResume() {
    super.onResume();
    System.out.println("Alarm manager setup");
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
    String prompts = prefs.getString("prompts", "5");
    String beginStr = prefs.getString("begin_time", "");
    String endStr = prefs.getString("end_time", "");
    Calendar beginCal = Calendar.getInstance();
    Calendar endCal = Calendar.getInstance();
    try {/* ww  w . j  av a2 s .c o m*/
        beginCal.setTime(sdf.parse(beginStr));
        endCal.setTime(sdf.parse(endStr));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    long interval = notificationIntervalCalculation(Integer.valueOf(prompts), beginCal, endCal);
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    Intent i = new Intent(context, NotificationService.class);
    PendingIntent pi = PendingIntent.getService(context, 0, i, 0);
    am.cancel(pi);

    // by my own convention, minutes <= 0 means notifications are disabled
    if (interval > 0) {
        am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + interval,
                interval, pi);
    }
}

From source file:edu.mit.media.funf.configured.ConfiguredPipeline.java

private void scheduleAlarm(String action, long delayInSeconds) {
    Intent i = new Intent(this, getClass());
    i.setAction(action);//from  ww  w  . j a v a  2 s  .co m
    boolean noAlarmExists = (PendingIntent.getService(this, 0, i, PendingIntent.FLAG_NO_CREATE) == null);
    if (noAlarmExists) {
        PendingIntent pi = PendingIntent.getService(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        long delayInMilliseconds = Utils.secondsToMillis(delayInSeconds);
        long startTimeInMilliseconds = System.currentTimeMillis() + delayInMilliseconds;
        Log.i(TAG, "Scheduling alarm for '" + action + "' at " + Utils.millisToSeconds(startTimeInMilliseconds)
                + " and every " + delayInSeconds + " seconds");
        // Inexact repeating doesn't work unlesss interval is 15, 30 min, or 1, 6, or 24 hours
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, startTimeInMilliseconds, delayInMilliseconds,
                pi);
    }
}

From source file:org.voidsink.anewjkuapp.utils.AppUtils.java

public static void updateSyncAlarm(Context context, boolean reCreateAlarm) {
    boolean mIsCalendarSyncEnabled = false;
    boolean mIsKusssSyncEnable = false;
    boolean mIsMasterSyncEnabled = ContentResolver.getMasterSyncAutomatically();

    if (mIsMasterSyncEnabled) {
        final Account mAccount = getAccount(context);
        if (mAccount != null) {
            mIsCalendarSyncEnabled = ContentResolver.getSyncAutomatically(mAccount,
                    CalendarContractWrapper.AUTHORITY());
            mIsKusssSyncEnable = ContentResolver.getSyncAutomatically(mAccount, KusssContentContract.AUTHORITY);
        }// w  w  w . j a va2 s .c  o  m
    }

    Log.d(TAG, String.format("MasterSync=%b, CalendarSync=%b, KusssSync=%b", mIsMasterSyncEnabled,
            mIsCalendarSyncEnabled, mIsKusssSyncEnable));

    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, SyncAlarmService.class);
    intent.putExtra(Consts.ARG_UPDATE_CAL, !mIsCalendarSyncEnabled);
    intent.putExtra(Consts.ARG_UPDATE_KUSSS, !mIsKusssSyncEnable);
    intent.putExtra(Consts.ARG_RECREATE_SYNC_ALARM, true);
    intent.putExtra(Consts.SYNC_SHOW_PROGRESS, true);

    // check if pending intent exists
    reCreateAlarm = reCreateAlarm
            || (PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_NO_CREATE) == null);

    // new pending intent
    PendingIntent alarmIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    if (!mIsMasterSyncEnabled || !mIsCalendarSyncEnabled || !mIsKusssSyncEnable) {
        if (reCreateAlarm) {
            long interval = PreferenceWrapper.getSyncInterval(context) * DateUtils.HOUR_IN_MILLIS;

            // synchronize in half an hour
            am.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                    System.currentTimeMillis() + AlarmManager.INTERVAL_HALF_HOUR, interval, alarmIntent);
        }
    } else {
        am.cancel(alarmIntent);
    }
}

From source file:ca.spencerelliott.mercury.ChangesetService.java

@Override
public void onStart(Intent intent, int startId) {
    int broadcast_call = intent.getIntExtra("ca.spencerelliott.mercury.call", -1);

    //If this was on boot we want to set up the alarm to set up repeating notifications
    if (broadcast_call == AlarmReceiver.ON_BOOT) {
        //Get the alarm service
        AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

        //Generate the interval between notifications, default to fifteen minutes
        long interval = Long.parseLong(prefs.getString("notification_interval", "900000"));

        //Create the intents to launch the service again
        Intent new_intent = new Intent("ca.spencerelliott.mercury.REFRESH_CHANGESETS");
        PendingIntent p_intent = PendingIntent.getBroadcast(this, 0, new_intent, 0);

        final Calendar c = Calendar.getInstance();

        //Create a repeating alarm
        alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, c.getTimeInMillis() + interval,
                interval, p_intent);//from   www .j av  a2s. c o m

        //Stop the service since we're waiting for the interval
        stopSelf();
    }

    //Create a new feed processor
    FeedProcessor processor = new FeedProcessor();

    //Gather all of the URLs from the databases here

    //Let the processor handle all of the URLs and notify the user of any new changesets
    processor.execute();

}

From source file:com.matthewmitchell.peercoin_android_wallet.WalletApplication.java

public void scheduleStartBlockchainService() {

    final WalletApplication wa = this;

    this.setOnLoadedCallback(new Runnable() {

        @Override//from  ww w.  ja  v a  2s .  c o m
        public void run() {

            final long lastUsedAgo = config.getLastUsedAgo();

            // apply some backoff
            final long alarmInterval;
            if (lastUsedAgo < Constants.LAST_USAGE_THRESHOLD_JUST_MS)
                alarmInterval = AlarmManager.INTERVAL_FIFTEEN_MINUTES;
            else if (lastUsedAgo < Constants.LAST_USAGE_THRESHOLD_RECENTLY_MS)
                alarmInterval = AlarmManager.INTERVAL_HALF_DAY;
            else
                alarmInterval = AlarmManager.INTERVAL_DAY;

            log.info("last used {} minutes ago, rescheduling blockchain sync in roughly {} minutes",
                    lastUsedAgo / DateUtils.MINUTE_IN_MILLIS, alarmInterval / DateUtils.MINUTE_IN_MILLIS);
            assertTrue(config != null);
            final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            final PendingIntent alarmIntent = PendingIntent.getService(wa, 0,
                    new Intent(wa, BlockchainServiceImpl.class), 0);
            alarmManager.cancel(alarmIntent);

            // workaround for no inexact set() before KitKat
            final long now = System.currentTimeMillis();
            alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, now + alarmInterval,
                    AlarmManager.INTERVAL_DAY, alarmIntent);

        }

    });

}

From source file:nerd.tuxmobil.fahrplan.congress.FahrplanMisc.java

public static long setUpdateAlarm(Context context, boolean initial) {
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    Intent alarmintent = new Intent(context, AlarmReceiver.class);
    alarmintent.setAction(AlarmReceiver.ALARM_UPDATE);

    PendingIntent pendingintent = PendingIntent.getBroadcast(context, 0, alarmintent, 0);

    MyApp.LogDebug(LOG_TAG, "set update alarm");
    long next_fetch;
    long interval;
    Time t = new Time();
    t.setToNow();/*from  www .  j  a  v a  2  s  .c o  m*/
    long now = t.toMillis(true);

    if ((now >= MyApp.first_day_start) && (now < MyApp.last_day_end)) {
        interval = 2 * AlarmManager.INTERVAL_HOUR;
        next_fetch = now + interval;
    } else if (now >= MyApp.last_day_end) {
        MyApp.LogDebug(LOG_TAG, "cancel alarm post congress");
        alarmManager.cancel(pendingintent);
        return 0;
    } else {
        interval = AlarmManager.INTERVAL_DAY;
        next_fetch = now + interval;
    }

    if ((now < MyApp.first_day_start) && ((now + AlarmManager.INTERVAL_DAY) >= MyApp.first_day_start)) {
        next_fetch = MyApp.first_day_start;
        interval = 2 * AlarmManager.INTERVAL_HOUR;
        if (!initial) {
            MyApp.LogDebug(LOG_TAG, "update alarm to interval " + interval + ", next in " + (next_fetch - now));
            alarmManager.cancel(pendingintent);
            alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, next_fetch, interval, pendingintent);
        }
    }

    if (initial) {
        MyApp.LogDebug(LOG_TAG,
                "set initial alarm to interval " + interval + ", next in " + (next_fetch - now));
        alarmManager.cancel(pendingintent);
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, next_fetch, interval, pendingintent);
    }

    return interval;
}

From source file:com.aero2.android.DefaultActivities.SmogMapActivity.java

public void setupAlarm(int hourOfDay) {
    //Alarm has been called
    ALARM_NOT_CALLED = false;/* w  w  w . j  a v a  2s .c o m*/

    //Setup what the alarm has to do when it goes off.
    Intent alarmIntent = new Intent(SmogMapActivity.this, AirAzureDownloadService.AlarmReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(SmogMapActivity.this, 0, alarmIntent,
            PendingIntent.FLAG_ONE_SHOT);//getBroadcast(context, 0, i, 0);
    Log.v("OnCreate", "Alarm Intent Created");

    //Set the AlarmManager to wake up the system every day at 6 a.m.
    AlarmManager am = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
    long timeEveryDay = calendar.getTimeInMillis();
    long currentTime = System.currentTimeMillis();
    long oneMin = 60 * 1000;
    am.setInexactRepeating(AlarmManager.RTC_WAKEUP, timeEveryDay, AlarmManager.INTERVAL_DAY, pi);
    if ((currentTime + oneMin) < timeEveryDay) {
        Log.v(LOG_TAG, "First time download and time is before 6 a.m.");
        Intent firstTimeDownloadIntent = new Intent(getApplicationContext(), AirAzureDownloadService.class);
        startService(firstTimeDownloadIntent);
    }
}

From source file:at.vcity.androidimsocket.services.IMService.java

public void authenticationResult(Object... args) {
    this.authenticatedUser = true;
    try {//w  w w . j  a va 2  s.co  m
        JSONObject param = new JSONObject(args[0].toString());
        String result = param.getString("result");
        if (result.equals(NetworkCommand.SUCCESSFUL)) {
            //currentUserId=param.getString("userId");
            FriendInfo f = new FriendInfo();
            f.userName = username;
            f.userId = param.getString("userId");
            Chatting.setCurrentUser(f);

            // getFriendList();

            AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(this, IMService.class);
            intent.putExtra("myToken", socketOperator.getToken());
            intent.putExtra("username", username);
            intent.putExtra("password", password);
            PendingIntent pintent = PendingIntent.getService(this, 0, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                    SystemClock.elapsedRealtime() + WAKE_TIME_PERIOD, WAKE_TIME_PERIOD, pintent);

            Intent loginintent = new Intent(TRY_LOGIN);
            loginintent.putExtra("AUTHENTICATION_RESULT", NetworkCommand.SUCCESSFUL);
            sendBroadcast(loginintent);

            // Start heartbeat
            heartIsBeating = true;
            startHeartbeat();
        } else {
            Toast.makeText(this, "Wrong user name", Toast.LENGTH_SHORT).show();
        }
    } catch (JSONException e) {
    }
    ;
}

From source file:cw.kop.autobackground.sources.SourceListFragment.java

/**
 * Starts (or stops) download and sets download icon appropriately
 *///from w  ww . j  av  a  2 s. c  om
private void startDownload() {
    listAdapter.saveData();
    if (FileHandler.isDownloading) {

        DialogFactory.ActionDialogListener listener = new DialogFactory.ActionDialogListener() {

            @Override
            public void onClickRight(View v) {
                FileHandler.cancel(appContext);
                resetActionBarDownload();
                dismissDialog();
            }
        };

        DialogFactory.showActionDialog(appContext, "", "Cancel download?", listener, -1, R.string.cancel_button,
                R.string.ok_button);
    } else if (FileHandler.download(appContext)) {
        Drawable drawable = getResources().getDrawable(R.drawable.ic_cancel_white_24dp);
        drawable.setColorFilter(AppSettings.getColorFilterInt(appContext), PorterDuff.Mode.MULTIPLY);
        toolbarMenu.getItem(1).setIcon(drawable);

        if (AppSettings.resetOnManualDownload() && AppSettings.useTimer()
                && AppSettings.getTimerDuration() > 0) {
            Intent intent = new Intent();
            intent.setAction(LiveWallpaperService.DOWNLOAD_WALLPAPER);
            intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(appContext, 0, intent, 0);
            AlarmManager alarmManager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
            alarmManager.cancel(pendingIntent);
            alarmManager.setInexactRepeating(AlarmManager.RTC,
                    System.currentTimeMillis() + AppSettings.getTimerDuration(), AppSettings.getTimerDuration(),
                    pendingIntent);
        }
    }
}