Example usage for android.app AlarmManager ELAPSED_REALTIME

List of usage examples for android.app AlarmManager ELAPSED_REALTIME

Introduction

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

Prototype

int ELAPSED_REALTIME

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

Click Source Link

Document

Alarm time in android.os.SystemClock#elapsedRealtime SystemClock.elapsedRealtime() (time since boot, including sleep).

Usage

From source file:org.proninyaroslav.libretorrent.services.TorrentTaskService.java

@Override
public void onTaskRemoved(Intent rootIntent) {
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
        Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
        restartServiceIntent.setPackage(getPackageName());

        PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1,
                restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);

        AlarmManager alarmService = (AlarmManager) getApplicationContext()
                .getSystemService(Context.ALARM_SERVICE);
        alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000,
                restartServicePendingIntent);
    }//from w w  w . ja  v  a  2 s  . c  om
}

From source file:com.embeddedlog.LightUpDroid.timer.TimerReceiver.java

private void showCollapsedNotificationWithNext(final Context context, String title, String text,
        Long nextBroadcastTime) {
    Intent activityIntent = new Intent(context, DeskClock.class);
    activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    activityIntent.putExtra(DeskClock.SELECT_TAB_INTENT_EXTRA, DeskClock.TIMER_TAB_INDEX);
    PendingIntent pendingActivityIntent = PendingIntent.getActivity(context, 0, activityIntent,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);
    showCollapsedNotification(context, title, text, Notification.PRIORITY_HIGH, pendingActivityIntent,
            IN_USE_NOTIFICATION_ID, false);

    if (nextBroadcastTime == null) {
        return;/*w  w w .  j a  v a2  s  .com*/
    }
    Intent nextBroadcast = new Intent();
    nextBroadcast.setAction(Timers.NOTIF_IN_USE_SHOW);
    PendingIntent pendingNextBroadcast = PendingIntent.getBroadcast(context, 0, nextBroadcast, 0);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    if (Utils.isKitKatOrLater()) {
        alarmManager.setExact(AlarmManager.ELAPSED_REALTIME, nextBroadcastTime, pendingNextBroadcast);
    } else {
        alarmManager.set(AlarmManager.ELAPSED_REALTIME, nextBroadcastTime, pendingNextBroadcast);
    }
}

From source file:com.android.deskclock.timer.TimerReceiver.java

private void showCollapsedNotificationWithNext(final Context context, String title, String text,
        Long nextBroadcastTime) {
    LogUtils.d(TAG, "showCollapsedNotificationWithNext nextBroadcastTime: %d", nextBroadcastTime);
    Intent activityIntent = new Intent(context, DeskClock.class);
    activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    activityIntent.putExtra(DeskClock.SELECT_TAB_INTENT_EXTRA, DeskClock.TIMER_TAB_INDEX);
    PendingIntent pendingActivityIntent = PendingIntent.getActivity(context, 0, activityIntent,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);
    showCollapsedNotification(context, title, text, NotificationCompat.PRIORITY_HIGH, pendingActivityIntent,
            IN_USE_NOTIFICATION_ID, false);

    if (nextBroadcastTime == null) {
        return;/*  ww  w . j  av  a2 s .  c om*/
    }
    Intent nextBroadcast = new Intent();
    nextBroadcast.setAction(Timers.NOTIF_IN_USE_SHOW);
    PendingIntent pendingNextBroadcast = PendingIntent.getBroadcast(context, 0, nextBroadcast, 0);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    if (Utils.isKitKatOrLater()) {
        alarmManager.setExact(AlarmManager.ELAPSED_REALTIME, nextBroadcastTime, pendingNextBroadcast);
    } else {
        alarmManager.set(AlarmManager.ELAPSED_REALTIME, nextBroadcastTime, pendingNextBroadcast);
    }
}

From source file:io.indy.drone.activity.StrikeListActivity.java

private void setupAlarm() {

    // check a SharedPreferences variable to see if we've already setup an inexact alarm
    // otherwise the time until the next alarm will reset every time StrikeListActivity
    // is used./*  w  w  w.  ja v a  2 s .c o m*/
    // var: time that the alarm was last triggered
    // if this was 2-3 hours ago the alarm was cancelled and requires a reset

    boolean requireAlarm = false;
    Date today = new Date();

    SharedPreferences settings = getSharedPreferences(ScheduledService.PREFS_FILENAME, 0);
    String alarmSetAt = settings.getString(ScheduledService.ALARM_SET_AT, "");
    if (alarmSetAt.isEmpty()) {
        // first time of running

        // don't check the server straight away since the db
        // might still be populating from the local json file
        //
        // startService(new Intent(this, ScheduledService.class));

        ifd("no alarm prefs found, assuming first time run, setting alarm");
        requireAlarm = true;
    } else {
        ifd("alarmSetAt = " + alarmSetAt);
        Date d = DateFormatHelper.parseSQLiteDateString(alarmSetAt);
        long diffMs = today.getTime() - d.getTime();
        long threeHours = 1000 * 60 * 60 * 3;
        if (diffMs > threeHours) {
            ifd("alarm was set more than 3 hours ago, and so requires a reset");
            requireAlarm = true;
        }
    }

    if (!requireAlarm) {
        ifd("no need to set an alarm from StrikeListActivity");
        return;
    }

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

    am = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
    am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,
            SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_HOUR, AlarmManager.INTERVAL_HOUR, pi);

    ifd("set alarm");

    SharedPreferences.Editor editor = settings.edit();
    editor.putString(ScheduledService.ALARM_SET_AT, DateFormatHelper.dateToSQLite(today));
    editor.commit();
    ifd("updated ALARM_SET_AT shared preference");
}

From source file:com.darshancomputing.BatteryIndicatorPro.BatteryInfoService.java

private void update(Intent intent) {
    now = System.currentTimeMillis();
    sps_editor = sp_service.edit();// ww  w  .ja v a 2  s.  c  om
    updated_lasts = false;

    if (intent != null)
        info.load(intent, sp_service);

    predictor.setPredictionType(
            settings.getString(SettingsActivity.KEY_PREDICTION_TYPE, str.default_prediction_type));
    predictor.update(info);
    info.prediction.updateRelativeTime();

    if (statusHasChanged())
        handleUpdateWithChangedStatus();
    else
        handleUpdateWithSameStatus();

    if (sp_service.getBoolean(KEY_SHOW_NOTIFICATION, true)) {
        prepareNotification();
        doNotify();
    }

    if (alarms.anyActiveAlarms())
        handleAlarms();

    updateWidgets(info);

    syncSpsEditor(); // Important to sync after other Service code that uses 'lasts' but before sending info to client

    for (Messenger messenger : clientMessengers) {
        // TODO: Can I send the same message to multiple clients instead of sending duplicates?
        sendClientMessage(messenger, RemoteConnection.CLIENT_BATTERY_INFO_UPDATED, info.toBundle());
    }

    alarmManager.set(AlarmManager.ELAPSED_REALTIME, android.os.SystemClock.elapsedRealtime() + (2 * 60 * 1000),
            updatePredictorPendingIntent);
}

From source file:net.imatruck.betterweather.BetterWeatherExtension.java

/**
 * Schedule an update with a {@link android.app.PendingIntent}
 *
 * @param intervalOverride Override in minutes for the next refresh, if 0 use settings value
 *///  w  w  w.j  a  v  a  2s .  co  m
private void scheduleRefresh(int intervalOverride) {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    sRefreshInterval = Integer.parseInt(sp.getString(PREF_WEATHER_REFRESH_INTERVAL, "60"));
    if (sRefreshInterval < 0) {
        WeatherRefreshReceiver.cancelPendingIntent(this);
        return;
    }

    int realRefreshInterval = sRefreshInterval;
    if (intervalOverride > 0)
        realRefreshInterval = intervalOverride;

    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    am.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + (realRefreshInterval * 60 * 1000),
            WeatherRefreshReceiver.getPendingIntent(this));
    LOGD(TAG, "Scheduled refresh in " + realRefreshInterval + " minutes.");
}

From source file:org.pixmob.freemobile.netstat.MonitorService.java

@Override
public void onTaskRemoved(Intent rootIntent) {
    if (prefs.getBoolean(SP_KEY_ENABLE_AUTO_RESTART_SERVICE, false) && Arrays
            .asList(ANDROID_VERSIONS_ALLOWED_TO_AUTO_RESTART_SERVICE).contains(Build.VERSION.RELEASE)) {
        // If task was removed, we should launch the service again.
        if (DEBUG)
            Log.d(TAG, "onTaskRemoved > setting alarm to restart service [ Kitkat START_STICKY bug ]");
        Intent restartService = new Intent(getApplicationContext(), this.getClass());
        restartService.setPackage(getPackageName());
        PendingIntent restartServicePI = PendingIntent.getService(getApplicationContext(), 1, restartService,
                PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmService = (AlarmManager) getApplicationContext()
                .getSystemService(Context.ALARM_SERVICE);
        alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePI);
    }/*from  www .  j av a  2  s  .  c o m*/

}

From source file:org.chromium.chrome.browser.physicalweb.UrlManager.java

private void scheduleClearNotificationAlarm() {
    PendingIntent pendingIntent = createClearNotificationAlarmIntent();
    AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
    long time = SystemClock.elapsedRealtime() + STALE_NOTIFICATION_TIMEOUT_MILLIS;
    alarmManager.set(AlarmManager.ELAPSED_REALTIME, time, pendingIntent);
}

From source file:org.numixproject.hermes.irc.IRCService.java

/**
 * Connect to the given server/*w w  w  .  j  av  a2s  .  c o m*/
 */
public void connect(final Server server) {
    final int serverId = server.getId();
    final int reconnectInterval = settings.getReconnectInterval() * 60000;
    final IRCService service = this;

    if (settings.isReconnectEnabled()) {
        server.setMayReconnect(true);
    }

    new Thread("Connect thread for " + server.getTitle()) {
        @Override
        public void run() {
            synchronized (alarmIntentsLock) {
                alarmIntents.remove(serverId);
                ReconnectReceiver lastReceiver = alarmReceivers.remove(serverId);
                if (lastReceiver != null) {
                    unregisterReceiver(lastReceiver);
                }
            }

            if (settings.isReconnectEnabled() && !server.mayReconnect()) {
                return;
            }

            try {
                IRCConnection connection = getConnection(serverId);

                connection.setNickname(server.getIdentity().getNickname());
                connection.setAliases(server.getIdentity().getAliases());
                connection.setIdent(server.getIdentity().getIdent());
                connection.setRealName(server.getIdentity().getRealName());
                connection.setUseSSL(server.useSSL());

                if (server.getCharset() != null) {
                    connection.setEncoding(server.getCharset());
                }

                if (server.getAuthentication().hasSaslCredentials()) {
                    connection.setSaslCredentials(server.getAuthentication().getSaslUsername(),
                            server.getAuthentication().getSaslPassword());
                }

                if (server.getPassword() != "") {
                    connection.connect(server.getHost(), server.getPort(), server.getPassword());
                } else {
                    connection.connect(server.getHost(), server.getPort());
                }
            } catch (Exception e) {
                server.setStatus(Status.DISCONNECTED);

                Intent sIntent = Broadcast.createServerIntent(Broadcast.SERVER_UPDATE, serverId);
                sendBroadcast(sIntent);

                IRCConnection connection = getConnection(serverId);

                Message message;

                if (e instanceof NickAlreadyInUseException) {
                    message = new Message(getString(R.string.nickname_in_use, connection.getNick()));
                    server.setMayReconnect(false);
                } else if (e instanceof IrcException) {
                    message = new Message(
                            getString(R.string.irc_login_error, server.getHost(), server.getPort()));
                    server.setMayReconnect(false);
                } else {
                    message = new Message(
                            getString(R.string.could_not_connect, server.getHost(), server.getPort()));
                    if (settings.isReconnectEnabled()) {
                        Intent rIntent = new Intent(Broadcast.SERVER_RECONNECT + serverId);
                        PendingIntent pendingRIntent = PendingIntent.getBroadcast(service, 0, rIntent, 0);
                        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
                        ReconnectReceiver receiver = new ReconnectReceiver(service, server);
                        synchronized (alarmIntentsLock) {
                            alarmReceivers.put(serverId, receiver);
                            registerReceiver(receiver, new IntentFilter(Broadcast.SERVER_RECONNECT + serverId));
                            am.set(AlarmManager.ELAPSED_REALTIME,
                                    SystemClock.elapsedRealtime() + reconnectInterval, pendingRIntent);
                            alarmIntents.put(serverId, pendingRIntent);
                        }
                    }
                }

                message.setColor(Message.COLOR_RED);
                message.setIcon(R.drawable.error);
                server.getConversation(ServerInfo.DEFAULT_NAME).addMessage(message);

                Intent cIntent = Broadcast.createConversationIntent(Broadcast.CONVERSATION_MESSAGE, serverId,
                        ServerInfo.DEFAULT_NAME);
                sendBroadcast(cIntent);
            }
        }
    }.start();
}

From source file:org.pixmob.freemobile.netstat.MonitorService.java

private void ensureServiceStaysRunning() {
    // KitKat appears to have (in some cases) forgotten how to honor START_STICKY
    // and if the service is killed, it doesn't restart.  On an emulator & AOSP device, it restarts...
    // on my CM device, it does not - WTF?  So, we'll make sure it gets back
    // up and running in a minimum of 10 minutes.  We reset our timer on a handler every
    // 2 minutes...but since the handler runs on uptime vs. the alarm which is on realtime,
    // it is entirely possible that the alarm doesn't get reset.  So - we make it a noop,
    // but this will still count against the app as a wakelock when it triggers.  Oh well,
    // it should never cause a device wakeup.  We're also at SDK 19 preferred, so the alarm
    // mgr set algorithm is better on memory consumption which is good.
    // http://stackoverflow.com/a/20735519/1527491
    if (prefs.getBoolean(SP_KEY_ENABLE_AUTO_RESTART_SERVICE, false) && Arrays
            .asList(ANDROID_VERSIONS_ALLOWED_TO_AUTO_RESTART_SERVICE).contains(Build.VERSION.RELEASE)) {
        if (DEBUG)
            Log.d(TAG, "ensureServiceStaysRunning > setting alarm. [ Kitkat START_STICKY bug ]");
        // A restart intent - this never changes...        
        final int restartAlarmInterval = 10 * 60 * 1000;
        final int resetAlarmTimer = 1 * 60 * 1000;
        final Intent restartIntent = new Intent(this, MonitorService.class);
        restartIntent.putExtra(INTENT_ALARM_RESTART_SERVICE_DIED, true);
        final AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Handler restartServiceHandler = new Handler() {
            @Override/*from www.jav  a 2 s  . c  o m*/
            public void handleMessage(Message msg) {
                // Create a pending intent
                PendingIntent pintent = PendingIntent.getService(getApplicationContext(), 0, restartIntent, 0);
                alarmMgr.set(AlarmManager.ELAPSED_REALTIME,
                        SystemClock.elapsedRealtime() + restartAlarmInterval, pintent);
                sendEmptyMessageDelayed(0, resetAlarmTimer);
            }
        };
        restartServiceHandler.sendEmptyMessageDelayed(0, 0);
    }
}