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.near.chimerarevo.activities.MainActivity.java

@Override
public void onDestroy() {
    super.onDestroy();
    if (ImageLoader.getInstance().isInited()) {
        ImageLoader.getInstance().clearDiskCache();
        ImageLoader.getInstance().clearMemoryCache();
    }//from   w ww .  ja  v  a  2 s. c  o  m
    if (mHelper != null)
        mHelper.dispose();

    if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("news_search_pref", true)) {
        Intent intent = new Intent(getApplicationContext(), NewsService.class);
        PendingIntent pintent = PendingIntent.getService(getApplicationContext(), 0, intent, 0);
        AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        alarm.cancel(pintent);

        long delay;
        int sel = Integer.parseInt(
                PreferenceManager.getDefaultSharedPreferences(this).getString("notification_delay_pref", "0"));

        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.embeddedlog.LightUpDroid.timer.TimerReceiver.java

private void updateNextTimesup(Context context) {
    TimerObj t = getNextRunningTimer(mTimers, false, Utils.getTimeNow());
    long nextTimesup = (t == null) ? -1 : t.getTimesupTime();
    int timerId = (t == null) ? -1 : t.mTimerId;

    Intent intent = new Intent();
    intent.setAction(Timers.TIMES_UP);//from w ww  .  j  av a 2s. c  om
    intent.setClass(context, TimerReceiver.class);
    if (!mTimers.isEmpty()) {
        intent.putExtra(Timers.TIMER_INTENT_EXTRA, timerId);
    }
    AlarmManager mngr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent p = PendingIntent.getBroadcast(context, 0, intent,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);
    if (t != null) {
        if (Utils.isKitKatOrLater()) {
            mngr.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, nextTimesup, p);
        } else {
            mngr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, nextTimesup, p);
        }
        if (Timers.LOGGING) {
            Log.d(TAG, "Setting times up to " + nextTimesup);
        }
    } else {
        mngr.cancel(p);
        if (Timers.LOGGING) {
            Log.v(TAG, "no next times up");
        }
    }
}

From source file:se.oort.clockify.timer.TimerReceiver.java

private void updateNextTimesup(Context context) {
    TimerObj t = getNextRunningTimer(mTimers, false, Utils.getTimeNow());
    long nextTimesup = (t == null) ? -1 : t.getTimesupTime();
    int timerId = (t == null) ? -1 : t.mTimerId;

    Intent intent = new Intent();
    intent.setAction(Timers.TIMES_UP);/*  w  w w .j av a  2 s  .  co m*/
    intent.setClass(context, TimerReceiver.class);
    if (!mTimers.isEmpty()) {
        intent.putExtra(Timers.TIMER_INTENT_EXTRA, timerId);
    }
    AlarmManager mngr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent p = PendingIntent.getBroadcast(context, 0, intent,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);
    if (t != null) {
        if (Utils.isKitKatOrLater()) {
            mngr.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, nextTimesup, p);
        } else {
            mngr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, nextTimesup, p);
        }
        if (Timers.LOGGING) {
            Log.d(LOG_TAG, "Setting times up to " + nextTimesup);
        }
    } else {
        mngr.cancel(p);
        if (Timers.LOGGING) {
            Log.v(LOG_TAG, "no next times up");
        }
    }
}

From source file:biz.bokhorst.bpt.BPTService.java

protected synchronized void startLocating() {
    // Start activity recognition
    if (activityRecognitionClient == null)
        activityRecognitionClient = new GoogleApiClient.Builder(this).addApi(ActivityRecognition.API)
                .addConnectionCallbacks(BPTService.this).build();

    // Connect activity recognition
    if (!activityRecognitionClient.isConnected() && !activityRecognitionClient.isConnecting()) {
        sendActivity(getString(R.string.connecting), -1, new Date().getTime());
        activityRecognitionClient.connect();
    }//from w  w w . j a v  a2  s  . c  o m

    // Schedule next alarm
    long interval = Integer.parseInt(
            preferences.getString(Preferences.PREF_TRACKINTERVAL, Preferences.PREF_TRACKINTERVAL_DEFAULT)) * 60L
            * 1000L;
    long alarmTime = SystemClock.elapsedRealtime() + interval;
    alarmManager.cancel(pendingAlarmIntent);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarmTime, pendingAlarmIntent);

    // Prepare user feedback
    nextTrackTime = new Date(System.currentTimeMillis() + interval);

    // Use activity recognition?
    boolean recognition = preferences.getBoolean(Preferences.PREF_ACTIVITYRECOGNITION,
            Preferences.PREF_ACTIVITYRECOGNITION_DEFAULT);

    if (recognition && !should)
        sendStage(String.format(getString(R.string.StageStill), TIME_FORMATTER.format(nextTrackTime)));

    if (!locating && (recognition ? should || once : true)) {
        locating = true;
        locationwait = false;
        wakeLock.acquire();

        // Start waiting for fix
        long timeout = Integer.parseInt(
                preferences.getString(Preferences.PREF_FIXTIMEOUT, Preferences.PREF_FIXTIMEOUT_DEFAULT))
                * 1000L;
        taskHandler.postDelayed(FixTimeoutTask, timeout);

        // Request location updates
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this,
                taskHandler.getLooper());
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this,
                taskHandler.getLooper());
        locationManager.addGpsStatusListener(this);

        // User feedback
        Date timeoutTime = new Date(System.currentTimeMillis() + timeout);
        boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        sendStage(String.format(getString(R.string.StageFixWait), TIME_FORMATTER.format(timeoutTime)));
        sendStatus(gpsEnabled ? getString(R.string.On) : getString(R.string.Off));
        sendSatellites(-1, -1);
    }
}

From source file:at.ac.uniklu.mobile.sportal.service.MutingService.java

/**
 * Schedules an alarm through the AlarmManager. Alarms are typically scheduled at time when courses begin or end.
 * @param time the time at which the alarm will go off
 * @param action the action that will be called when the alarm goes off
 *//*  w  w  w  .j  a v a 2  s . c  o m*/
private void scheduleAlarm(long time, int action, int alarmId) {
    Log.d(TAG, "scheduling alarm action " + action + " @ " + new Date(time).toLocaleString() + " (aID:"
            + alarmId + ")");

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    Intent alarmIntent = new Intent(this, OnAlarmReceiver.class).putExtra(ACTION, action)
            .putExtra(EXTRA_ALARM_ID, alarmId);
    PendingIntent pendingAlarmIntent = PendingIntent.getBroadcast(this, 0, alarmIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    time = SystemClock.elapsedRealtime() + (time - System.currentTimeMillis()); //  convert unixtime to system runtime
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, time, pendingAlarmIntent);
}

From source file:net.networksaremadeofstring.rhybudd.ZenossPoller.java

private void PollerCheck() {
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    Intent Poller = new Intent(this, ZenossPoller.class);

    if (settings.getBoolean("AllowBackgroundService", true)) {
        //Log.i("PollerCheck","Background scanning enabled!");
        Notifications.SendStickyNotification(this);

        Poller.putExtra("events", true);
        PendingIntent Monitoring = PendingIntent.getService(this, 0, Poller, PendingIntent.FLAG_UPDATE_CURRENT);//PendingIntent.FLAG_UPDATE_CURRENT
        am.cancel(Monitoring);/*from ww w  .java 2 s  . c om*/
        try {
            am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, (long) 0,
                    Long.parseLong(settings.getString("BackgroundServiceDelay", "60")) * 1000, Monitoring);
        } catch (Exception e) {
            am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, (long) 0, 60000, Monitoring);
            BugSenseHandler.sendExceptionMessage("ZenossPoller", "PollerCheck", e);
        }
    } else {
        //Log.i("PollerCheck","Background scanning disabled!");
        Poller.putExtra("events", true);
        PendingIntent Monitoring = PendingIntent.getService(this, 0, Poller, PendingIntent.FLAG_UPDATE_CURRENT);//PendingIntent.FLAG_UPDATE_CURRENT
        am.cancel(Monitoring);
        mNM.cancel(Notifications.NOTIFICATION_POLLED_STICKY);
    }

    /*if(settings.getBoolean("refreshCache", true))
    {
       //Log.i("PollerCheck","Background cache refresh enabled!");
               
       Poller.putExtra("refreshCache", true);
       PendingIntent CacheRefresh = PendingIntent.getService(this, 1, Poller, PendingIntent.FLAG_UPDATE_CURRENT);
       am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, 10000, AlarmManager.INTERVAL_HOUR, CacheRefresh);
    }
    else
    {
       //Log.i("PollerCheck","Background cache refresh disabled!");
       Poller.putExtra("refreshCache", true);
       PendingIntent CacheRefresh = PendingIntent.getService(this, 1, Poller, PendingIntent.FLAG_UPDATE_CURRENT);
       am.cancel(CacheRefresh);
    }*/

    //We use a SyncAdapter now like good citizens
    try {
        if (settings.getBoolean("refreshCache", true)) {
            Poller.putExtra("refreshCache", true);
            PendingIntent CacheRefresh = PendingIntent.getService(this, 1, Poller,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            am.cancel(CacheRefresh);
            SharedPreferences.Editor editor = settings.edit();
            editor.putBoolean("refreshCache", false);
            editor.commit();
        }
    } catch (Exception e) {
        e.printStackTrace();
        BugSenseHandler.sendExceptionMessage("ZenossPoller", "cancel refresh cache poller", e);
    }
}

From source file:com.github.jvanhie.discogsscrobbler.util.NowPlayingService.java

private void play(final int trackNumber) {
    //do we even have something to play?
    if (trackList == null || trackList.size() == 0)
        return;//from w ww  .  j a  v  a2  s  .  c  om

    track = trackList.get(trackNumber);

    //don't play headings, on to the next! (if there is a next)
    if (track.type.equals("heading")) {
        if (trackNumber + 1 < trackList.size()) {
            play(trackNumber + 1);
        } else {
            stop();
        }
        return;
    }

    isPlaying = true;
    artist = track.artist;
    album = track.album;
    currentTrack = trackNumber;
    mNotificationBuilder.setContentTitle(track.title).setContentText(track.artist + " - " + track.album)
            .setWhen(System.currentTimeMillis()).setSmallIcon(android.R.drawable.ic_media_play);
    //fetch the duration (will return immediately when available) and start the alarm for when it's done
    mLastfm.getDuration(track, new Lastfm.LastfmWaiter() {
        @Override
        public void onResult(boolean success) {
            //set nowplaying, scrobbling happens on the alarm callback
            mLastfm.updateNowPlaying(track, new Lastfm.LastfmWaiter() {
                @Override
                public void onResult(boolean success) {
                    //the user already sees the notification, no need for extras notifications atm.
                }
            });

            //notify user
            startForeground(NOTIFICATION_ID, mNotificationBuilder.build());
            //update listeners to track change
            sendBroadcast(new Intent(TRACK_CHANGE));

            Intent intent = new Intent(NowPlayingService.this, NowPlayingAlarm.class);
            if (trackNumber < trackList.size() - 1) {
                intent.putExtra(NEXT_TRACK_ID, (trackNumber + 1));
                intent.putExtra(NEXT_TRACK_TITLE, trackList.get(trackNumber + 1).title);
            } else {
                //this is the last track, alarm will be used to stop the service (by issuing pos = -1 and title = first song title)
                intent.putExtra(NEXT_TRACK_ID, -1);
                intent.putExtra(NEXT_TRACK_TITLE, trackList.get(0).title);
            }
            mTrackStart = SystemClock.elapsedRealtime();
            int duration = Track.formatDurationToSeconds(track.duration);
            if (duration == 0)
                duration = Lastfm.DEFAULT_TRACK_DURATION;
            if (mTrackDone != 0)
                duration -= mTrackDone;
            mAlarmIntent = PendingIntent.getBroadcast(NowPlayingService.this, 0, intent,
                    PendingIntent.FLAG_CANCEL_CURRENT);
            mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, mTrackStart + duration * 1000,
                    mAlarmIntent);

        }
    });

}

From source file:org.traccar.client.MainFragment.java

private void startTrackingService(boolean checkPermission, boolean permission) {
    if (checkPermission) {
        Set<String> missingPermissions = new HashSet<>();
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            missingPermissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }/*from w ww.jav  a2 s . c  o  m*/
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            missingPermissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }
        if (missingPermissions.isEmpty()) {
            permission = true;
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(missingPermissions.toArray(new String[missingPermissions.size()]),
                        PERMISSIONS_REQUEST_LOCATION);
            }
            return;
        }
    }

    if (permission) {
        setPreferencesEnabled(false);
        ContextCompat.startForegroundService(getActivity(), new Intent(getActivity(), TrackingService.class));
        alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, ALARM_MANAGER_INTERVAL,
                ALARM_MANAGER_INTERVAL, alarmIntent);
    } else {
        sharedPreferences.edit().putBoolean(KEY_STATUS, false).apply();
        TwoStatePreference preference = (TwoStatePreference) findPreference(KEY_STATUS);
        preference.setChecked(false);
    }
}

From source file:uk.org.rivernile.edinburghbustracker.android.alerts.TimeAlertService.java

/**
 * Reschedule the retrieval of bus times from the server because there was
 * an error loading them or the service/time criteria has not been met.
 * //from   w w  w . jav  a  2 s  . co  m
 * If the rescheduling goes on for an hour, then cancel the checking and
 * remove the alert otherwise the user's battery will be drained and data
 * used.
 * 
 * @param intent The intent that started this service. This is to be reused
 * to start the next service at the appropriate time.
 */
private void reschedule(final Intent intent) {
    final long timeSet = intent.getLongExtra(ARG_TIME_SET, 0);

    // Checks to see if the alert has been active for the last hour or more.
    // If so, it gets cancelled.
    if ((SystemClock.elapsedRealtime() - timeSet) >= 3600000) {
        alertMan.removeTimeAlert();
        return;
    }

    final PendingIntent pi = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    // Reschedule ourself to run again in 60 seconds.
    alarmMan.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 60000, pi);
}

From source file:com.hhunj.hhudata.ForegroundService.java

protected void clockRing() {
    Intent intent = new Intent(this, RepeatingAlarm.class);

    PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);

    long firstTime = m_workStartTime.getTime();
    long elaps = 24 * 60 * 60 * 1000;
    //long elaps = 15 * 1000;
    // Schedule the alarm!
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, elaps, sender);

    // Tell the user about what we did.
    if (mToast != null) {
        mToast.cancel();//  w  w w. j av  a 2  s. c  o  m
    }
    mToast = Toast.makeText(this, "R.string.repeating_scheduled", Toast.LENGTH_LONG);
    mToast.show();

}