Example usage for android.app AlarmManager ELAPSED_REALTIME_WAKEUP

List of usage examples for android.app AlarmManager ELAPSED_REALTIME_WAKEUP

Introduction

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

Prototype

int ELAPSED_REALTIME_WAKEUP

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

Click Source Link

Document

Alarm time in android.os.SystemClock#elapsedRealtime SystemClock.elapsedRealtime() (time since boot, including sleep), which will wake up the device when it goes off.

Usage

From source file:com.group13.androidsdk.mycards.NotificationService.java

private void rescheduleNotifications() {

    List<NotificationRule> rules = new ArrayList<>();
    Collections.addAll(rules, MyCardsDBManager.getInstance(this).getAllNotificationRules());
    rules.addAll(getCalendarAsNotificationRules());

    SharedPreferences prefs = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
    long lastNotifMillis = prefs.getLong("lastNotifElapsedRealtime", -2 * FIFTEEN_MINUTES);
    SharedPreferences.Editor prefEditor = prefs.edit();

    MyCardsDBManager dbm = MyCardsDBManager.getInstance(this);
    if (!(Math.abs(lastNotifMillis - SystemClock.elapsedRealtime()) < FIFTEEN_MINUTES || dbm.getDoNotDisturb()
            || dateMatchesAnyRule(new Date(), rules)
            || dbm.getCardsForReviewBefore(new Date(), null).length == 0)) {
        lastNotifMillis = SystemClock.elapsedRealtime();
        prefEditor.putLong("lastNotifElapsedRealtime", lastNotifMillis);

        sendNotification();/*w  w  w .  j  a v  a  2s  .c  o m*/
    }

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

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + FIFTEEN_MINUTES, pi);

    prefEditor.putLong("lastRunElapsedRealtime", SystemClock.elapsedRealtime());
    prefEditor.apply();
}

From source file:cc.softwarefactory.lokki.android.androidServices.LocationService.java

private void setTemporalTimer() {
    AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
    Intent alarmIntent = new Intent(this, LocationService.class);
    alarmIntent.putExtra(ALARM_TIMER, 1);
    PendingIntent alarmCallback = PendingIntent.getService(this, 0, alarmIntent, 0);
    alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + INTERVAL_1_MIN,
            alarmCallback);//from  w w w. j a v a  2  s .c om
    Log.d(TAG, "Time created.");
}

From source file:com.hedgehog.smdb.ActionBarControlScrollViewActivity.java

private void repeat() {
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override/*from  ww w .  ja v  a  2 s.  c  o m*/
        public void onReceive(Context context, Intent intent) {
            showNotification();
        }
    };

    this.registerReceiver(receiver, new IntentFilter("TecxiDriverCheckingForConfirmedBids"));
    PendingIntent pintent = PendingIntent.getBroadcast(this, 0,
            new Intent("TecxiDriverCheckingForConfirmedBids"), 0);
    AlarmManager manager = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
    manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0, 1000 * 60 * 30, pintent);
}

From source file:org.wso2.iot.agent.services.AgentStartupReceiver.java

/**
 * Initiates device notifier on device startup.
 * @param context - Application context.
 *///from  ww  w.  j a v a  2  s. co m
private void setRecurringAlarm(Context context) {
    Resources resources = context.getApplicationContext().getResources();
    String mode = Preference.getString(context, Constants.PreferenceFlag.NOTIFIER_TYPE);
    boolean isLocked = Preference.getBoolean(context, Constants.IS_LOCKED);
    String lockMessage = Preference.getString(context, Constants.LOCK_MESSAGE);

    if (lockMessage == null || lockMessage.isEmpty()) {
        lockMessage = resources.getString(R.string.txt_lock_activity);
    }

    if (isLocked) {
        Operation lockOperation = new Operation();
        lockOperation.setId(DEFAULT_ID);
        lockOperation.setCode(Constants.Operation.DEVICE_LOCK);
        try {
            JSONObject payload = new JSONObject();
            payload.put(Constants.ADMIN_MESSAGE, lockMessage);
            payload.put(Constants.IS_HARD_LOCK_ENABLED, true);
            lockOperation.setPayLoad(payload.toString());
            OperationProcessor operationProcessor = new OperationProcessor(context);
            operationProcessor.doTask(lockOperation);
        } catch (AndroidAgentException e) {
            Log.e(TAG, "Error occurred while executing hard lock operation at the device startup");
        } catch (JSONException e) {
            Log.e(TAG, "Error occurred while building hard lock operation payload");
        }
    }

    int interval = Preference.getInt(context, context.getResources().getString(R.string.shared_pref_frequency));
    if (interval == DEFAULT_INT_VALUE) {
        interval = Constants.DEFAULT_INTERVAL;
    }

    if (mode == null) {
        mode = Constants.NOTIFIER_LOCAL;
    }

    if (Preference.getBoolean(context, Constants.PreferenceFlag.REGISTERED)
            && Constants.NOTIFIER_LOCAL.equals(mode.trim().toUpperCase(Locale.ENGLISH))) {

        Intent alarmIntent = new Intent(context, AlarmReceiver.class);
        PendingIntent recurringAlarmIntent = PendingIntent.getBroadcast(context, Constants.DEFAULT_REQUEST_CODE,
                alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, Constants.DEFAULT_START_INTERVAL,
                interval, recurringAlarmIntent);
        Log.i(TAG, "Setting up alarm manager for polling every " + interval + " milliseconds.");
    }
}

From source file:com.near.chimerarevo.fragments.SettingsFragment.java

private void setAlarm(int sel, boolean isEnabled) {
    Intent intent = new Intent(getActivity().getApplicationContext(), NewsService.class);
    PendingIntent pintent = PendingIntent.getService(getActivity().getApplicationContext(), 0, intent, 0);
    AlarmManager alarm = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);

    alarm.cancel(pintent);//from   w  ww  . java 2 s .c  o  m

    if (isEnabled) {
        long delay;
        switch (sel) {
        case 0:
            delay = AlarmManager.INTERVAL_FIFTEEN_MINUTES;
            break;
        case 1:
            delay = AlarmManager.INTERVAL_HALF_HOUR;
            break;
        case 2:
            delay = AlarmManager.INTERVAL_HOUR;
            break;
        case 3:
            delay = 2 * AlarmManager.INTERVAL_HOUR;
            break;
        case 4:
            delay = 3 * AlarmManager.INTERVAL_HOUR;
            break;
        case 5:
            delay = 6 * AlarmManager.INTERVAL_HOUR;
            break;
        case 6:
            delay = AlarmManager.INTERVAL_HALF_DAY;
            break;
        case 7:
            delay = AlarmManager.INTERVAL_DAY;
            break;
        default:
            delay = AlarmManager.INTERVAL_HOUR;
            break;
        }

        alarm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.uptimeMillis(), delay, pintent);
    }
}

From source file:com.android.cts.verifier.sensors.SignificantMotionTestActivity.java

@SuppressWarnings("unused")
public String testAPWakeUpOnSMDTrigger() throws Throwable {
    SensorTestLogger logger = getTestLogger();
    logger.logInstructions(R.string.snsr_significant_motion_ap_suspend);
    waitForUserToBegin();//from  w w w  . j av  a 2 s.c  o  m
    mVerifier = new TriggerVerifier();
    mSensorManager.requestTriggerSensor(mVerifier, mSensorSignificantMotion);
    long testStartTimeNs = SystemClock.elapsedRealtimeNanos();
    Handler handler = new Handler(Looper.getMainLooper());
    SuspendStateMonitor suspendStateMonitor = new SuspendStateMonitor();

    Intent intent = new Intent(this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    am.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + ALARM_WAKE_TIME_DELAY_MS,
            pendingIntent);
    try {
        // Wait for the first event to trigger. Device is expected to go into suspend here.
        mVerifier.verifyEventTriggered();
        long eventTimeStampNs = mVerifier.getTimeStampForTriggerEvent();
        long endTimeNs = SystemClock.elapsedRealtimeNanos();
        long lastWakeupTimeNs = TimeUnit.MILLISECONDS.toNanos(suspendStateMonitor.getLastWakeUpTime());
        Assert.assertTrue(getString(R.string.snsr_device_did_not_go_into_suspend),
                testStartTimeNs < lastWakeupTimeNs && lastWakeupTimeNs < endTimeNs);
        long timestampDelta = Math.abs(lastWakeupTimeNs - eventTimeStampNs);
        Assert.assertTrue(
                String.format(getString(R.string.snsr_device_did_not_wake_up_at_trigger),
                        TimeUnit.NANOSECONDS.toMillis(lastWakeupTimeNs),
                        TimeUnit.NANOSECONDS.toMillis(eventTimeStampNs)),
                timestampDelta < MAX_ACCEPTABLE_DELAY_EVENT_AP_WAKE_UP_NS);
    } finally {
        am.cancel(pendingIntent);
        suspendStateMonitor.cancel();
        mScreenManipulator.turnScreenOn();
        playSound();
    }
    return null;
}

From source file:no.ntnu.idi.socialhitchhiking.SocialHitchhikingApplication.java

/**
 * Starts a service that will poll the server for updates at a regular time interval.
 * It will start 10 sec after the app is started, then poll according to the update interval 
 * chosen in settings. /*from  w  w  w . j  a va 2s.  c om*/
 */
public void startService() {
    Intent intent = new Intent(this, AlarmService.class);
    service = PendingIntent.getBroadcast(this, 0, intent, 0);
    long firstTime = SystemClock.elapsedRealtime();
    firstTime += 10 * 1000;
    am.cancel(service);

    int interval = Integer.valueOf(getSettings().getUpdateInterval());
    am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, interval * 1000, service);
    keyMap.put("alarmService", true);
}

From source file:alaindc.crowdroid.SensorsIntentService.java

public void stub_onSensorChanged(int typeSensor) {
    if (typeSensor < 0)
        return;//from  www. j  av  a2  s . c  o  m

    float value, minf, maxf;
    switch (typeSensor) {
    case Sensor.TYPE_AMBIENT_TEMPERATURE:
        minf = -20;
        maxf = 42;
        break;
    case Sensor.TYPE_PRESSURE: // https://it.wikipedia.org/wiki/Pressione_atmosferica
        minf = 870;
        maxf = 1085;
        break;
    case Sensor.TYPE_RELATIVE_HUMIDITY:
        minf = 30;
        maxf = 100;
        break;
    default:
        minf = 0;
        maxf = 0;
        break;
    }

    value = random.nextFloat() * (maxf - minf) + minf;

    int index = Constants.getIndexAlarmForSensor(typeSensor);

    SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(Constants.PREF_FILE,
            Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putString(Constants.PREF_SENSOR_ + typeSensor, Float.toString(value));
    editor.commit();

    // Update view
    Intent senseintent = new Intent(Constants.INTENT_UPDATE_SENSORS);
    senseintent.putExtra(Constants.INTENT_RECEIVED_DATA_EXTRA_DATA,
            "Sensor " + Constants.getNameOfSensor(typeSensor) + " value: " + Float.toString(value));
    LocalBroadcastManager.getInstance(this).sendBroadcast(senseintent);

    // Set the alarm random
    alarmMgr = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    Intent intentAlarm = new Intent(getApplicationContext(), SensorsIntentService.class);
    intentAlarm.setAction(Constants.INTENT_STUB_SENSOR_CHANGED + typeSensor);
    intentAlarm.putExtra(Constants.INTENT_STUB_SENSOR_CHANGED_TYPE, typeSensor);
    alarmIntent = PendingIntent.getService(getApplicationContext(), 0, intentAlarm, 0);

    // TODO Set timeout time from server indications
    int seconds = random.nextInt(50) + 10; // 10/60 sec
    alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + seconds * 1000,
            alarmIntent);
}

From source file:no.ntnu.idi.socialhitchhiking.SocialHitchhikingApplication.java

/**
 * Starts a service that checks if there is a scheduled Journey in less than one hour.
 * It will start one minute after the app is started, then poll every ten minutes.
 *//*from   ww  w  .  j a  v  a 2s .co m*/
public void startJourneyReminder() {
    Intent intent = new Intent(this, JourneyReminder.class);
    journeyReminder = PendingIntent.getBroadcast(this, 0, intent, 0);
    am.cancel(journeyReminder);

    int tenMinutes = 600000;
    am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, tenMinutes / 10, tenMinutes, journeyReminder);
}

From source file:io.demiseq.jetreader.activities.MainActivity.java

private void setAlarmService() {
    if (!prefs.getBoolean("Alarm", false)) {
        Intent i = new Intent(this, FetchLatestService.class);
        PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.cancel(pi);//from  ww w .  j  a v  a 2  s  .  c o m
        String frequency = prefs.getString(GeneralSettingsActivity.KEY_UPDATE_FREQUENCY, "1440");
        int minute = Integer.parseInt(frequency);
        am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + minute * 60 * 1000, minute * 60 * 1000, pi);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean("Alarm", true);
        editor.apply();
    }
}