Example usage for android.os SystemClock elapsedRealtime

List of usage examples for android.os SystemClock elapsedRealtime

Introduction

In this page you can find the example usage for android.os SystemClock elapsedRealtime.

Prototype

@CriticalNative
native public static long elapsedRealtime();

Source Link

Document

Returns milliseconds since boot, including time spent in sleep.

Usage

From source file:android.provider.Checkin.java

/**
 * Helper function to report a crash.//w w w  .  java  2 s  .c  o m
 *
 * @param resolver from {@link android.content.Context#getContentResolver}
 * @param crash data from {@link android.server.data.CrashData}
 * @return URI of the crash report that was added
 */
static public Uri reportCrash(ContentResolver resolver, byte[] crash) {
    try {
        // If we are in a situation where crash reports fail (such as a full disk),
        // it's important that we don't get into a loop trying to report failures.
        // So discard all crash reports for a few seconds after reporting fails.
        long realtime = SystemClock.elapsedRealtime();
        if (realtime - sLastCrashFailureRealtime < MIN_CRASH_FAILURE_RETRY) {
            Log.e(TAG, "Crash logging skipped, too soon after logging failure");
            return null;
        }

        // HACK: we don't support BLOB values, so base64 encode it.
        byte[] encoded = Base64.encodeBase64(crash);
        ContentValues values = new ContentValues();
        values.put(Crashes.DATA, new String(encoded));
        Uri uri = resolver.insert(Crashes.CONTENT_URI, values);
        if (uri == null) {
            Log.e(TAG, "Error reporting crash");
            sLastCrashFailureRealtime = SystemClock.elapsedRealtime();
        }
        return uri;
    } catch (Throwable t) {
        // To avoid an infinite crash-reporting loop, swallow all errors and exceptions.
        Log.e(TAG, "Error reporting crash: " + t);
        sLastCrashFailureRealtime = SystemClock.elapsedRealtime();
        return null;
    }
}

From source file:com.securecomcode.text.service.KeyCachingService.java

private void startTimeoutIfAppropriate() {
    boolean timeoutEnabled = TextSecurePreferences.isPassphraseTimeoutEnabled(this);

    if ((activitiesRunning == 0) && (this.masterSecret != null) && timeoutEnabled
            && !TextSecurePreferences.isPasswordDisabled(this)) {
        long timeoutMinutes = TextSecurePreferences.getPassphraseTimeoutInterval(this);
        long timeoutMillis = timeoutMinutes * 60 * 1000;

        Log.w("KeyCachingService", "Starting timeout: " + timeoutMillis);

        AlarmManager alarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE);
        alarmManager.cancel(pending);//  ww w .ja v  a2 s.com
        alarmManager.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + timeoutMillis, pending);
    }
}

From source file:ai.eve.volley.Request.java

/**
 * Notifies the request queue that this request has finished (successfully
 * or with error)./*from w  w  w.  j  av a 2s  . c o m*/
 * 
 * <p>
 * Also dumps all events from this request's event log; for debugging.
 * </p>
 */
public void finish(final String tag) {
    if (mRequestQueue != null) {
        mRequestQueue.finish(this);
    }
    if (MarkerLog.ENABLED) {
        final long threadId = Thread.currentThread().getId();
        if (Looper.myLooper() != Looper.getMainLooper()) {
            // If we finish marking off of the main thread, we need to
            // actually do it on the main thread to ensure correct ordering.
            Handler mainThread = new Handler(Looper.getMainLooper());
            mainThread.post(new Runnable() {
                @Override
                public void run() {
                    mEventLog.add(tag, threadId);
                    mEventLog.finish(this.toString());
                }
            });
            return;
        }

        mEventLog.add(tag, threadId);
        mEventLog.finish(this.toString());
    } else {
        long requestTime = SystemClock.elapsedRealtime() - mRequestBirthTime;
        if (requestTime >= SLOW_REQUEST_THRESHOLD_MS) {
            NetroidLog.d("%d ms: %s", requestTime, this.toString());
        }
    }
}

From source file:com.android.deskclock.data.TimerNotificationBuilderPreN.java

@Override
public Notification build(Context context, NotificationModel nm, List<Timer> unexpired) {
    final Timer timer = unexpired.get(0);
    final long remainingTime = timer.getRemainingTime();

    // Generate some descriptive text, a title, and some actions based on timer states.
    final String contentText;
    final String contentTitle;
    @DrawableRes/*from  w  w w .ja va  2 s  . c om*/
    int firstActionIconId, secondActionIconId = 0;
    @StringRes
    int firstActionTitleId, secondActionTitleId = 0;
    Intent firstActionIntent, secondActionIntent = null;

    if (unexpired.size() == 1) {
        contentText = formatElapsedTimeUntilExpiry(context, remainingTime);

        if (timer.isRunning()) {
            // Single timer is running.
            if (TextUtils.isEmpty(timer.getLabel())) {
                contentTitle = context.getString(R.string.timer_notification_label);
            } else {
                contentTitle = timer.getLabel();
            }

            firstActionIconId = R.drawable.ic_pause_24dp;
            firstActionTitleId = R.string.timer_pause;
            firstActionIntent = new Intent(context, TimerService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_PAUSE_TIMER)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId());

            secondActionIconId = R.drawable.ic_add_24dp;
            secondActionTitleId = R.string.timer_plus_1_min;
            secondActionIntent = new Intent(context, TimerService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_ADD_MINUTE_TIMER)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId());
        } else {
            // Single timer is paused.
            contentTitle = context.getString(R.string.timer_paused);

            firstActionIconId = R.drawable.ic_start_24dp;
            firstActionTitleId = R.string.sw_resume_button;
            firstActionIntent = new Intent(context, TimerService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_START_TIMER)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId());

            secondActionIconId = R.drawable.ic_reset_24dp;
            secondActionTitleId = R.string.sw_reset_button;
            secondActionIntent = new Intent(context, TimerService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_RESET_TIMER)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId());
        }
    } else {
        if (timer.isRunning()) {
            // At least one timer is running.
            final String timeRemaining = formatElapsedTimeUntilExpiry(context, remainingTime);
            contentText = context.getString(R.string.next_timer_notif, timeRemaining);
            contentTitle = context.getString(R.string.timers_in_use, unexpired.size());
        } else {
            // All timers are paused.
            contentText = context.getString(R.string.all_timers_stopped_notif);
            contentTitle = context.getString(R.string.timers_stopped, unexpired.size());
        }

        firstActionIconId = R.drawable.ic_reset_24dp;
        firstActionTitleId = R.string.timer_reset_all;
        firstActionIntent = TimerService.createResetUnexpiredTimersIntent(context);
    }

    // Intent to load the app and show the timer when the notification is tapped.
    final Intent showApp = new Intent(context, HandleDeskClockApiCalls.class)
            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).setAction(HandleDeskClockApiCalls.ACTION_SHOW_TIMERS)
            .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId())
            .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, R.string.label_notification);

    final PendingIntent pendingShowApp = PendingIntent.getActivity(context, 0, showApp,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setOngoing(true)
            .setLocalOnly(true).setShowWhen(false).setAutoCancel(false).setContentText(contentText)
            .setContentTitle(contentTitle).setContentIntent(pendingShowApp)
            .setSmallIcon(R.drawable.stat_notify_timer).setPriority(NotificationCompat.PRIORITY_HIGH)
            .setCategory(NotificationCompat.CATEGORY_ALARM).setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setColor(ContextCompat.getColor(context, R.color.default_background));

    final PendingIntent action1 = Utils.pendingServiceIntent(context, firstActionIntent);
    final String action1Title = context.getString(firstActionTitleId);
    builder.addAction(firstActionIconId, action1Title, action1);

    if (secondActionIntent != null) {
        final PendingIntent action2 = Utils.pendingServiceIntent(context, secondActionIntent);
        final String action2Title = context.getString(secondActionTitleId);
        builder.addAction(secondActionIconId, action2Title, action2);
    }

    final AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    final Intent updateNotification = TimerService.createUpdateNotificationIntent(context);
    if (timer.isRunning() && remainingTime > MINUTE_IN_MILLIS) {
        // Schedule a callback to update the time-sensitive information of the running timer.
        final PendingIntent pi = PendingIntent.getService(context, 0, updateNotification,
                PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

        final long nextMinuteChange = remainingTime % MINUTE_IN_MILLIS;
        final long triggerTime = SystemClock.elapsedRealtime() + nextMinuteChange;
        TimerModel.schedulePendingIntent(am, triggerTime, pi);
    } else {
        // Cancel the update notification callback.
        final PendingIntent pi = PendingIntent.getService(context, 0, updateNotification,
                PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_NO_CREATE);
        if (pi != null) {
            am.cancel(pi);
            pi.cancel();
        }
    }

    return builder.build();
}

From source file:com.boko.vimusic.ui.activities.AudioPlayerActivity.java

/**
 * {@inheritDoc}// w  w w  .  j a  va 2 s . c  o m
 */
@Override
public void onProgressChanged(final SeekBar bar, final int progress, final boolean fromuser) {
    if (!fromuser || mService == null) {
        return;
    }
    final long now = SystemClock.elapsedRealtime();
    if (now - mLastSeekEventTime > 250) {
        mLastSeekEventTime = now;
        mLastShortSeekEventTime = now;
        mPosOverride = MusicUtils.duration() * progress / 1000;
        MusicUtils.seek(mPosOverride);
        if (!mFromTouch) {
            // refreshCurrentTime();
            mPosOverride = -1;
        }
    } else if (now - mLastShortSeekEventTime > 5) {
        mLastShortSeekEventTime = now;
        mPosOverride = MusicUtils.duration() * progress / 1000;
        refreshCurrentTimeText(mPosOverride);
    }
}

From source file:com.onyx.deskclock.deskclock.data.StopwatchModel.java

/**
 * Updates the notification to reflect the latest state of the stopwatch and recorded laps.
 *//*from   w w w. ja  va2  s. c om*/
void updateNotification() {
    final Stopwatch stopwatch = getStopwatch();

    // Notification should be hidden if the stopwatch has no time or the app is open.
    if (stopwatch.isReset() || mNotificationModel.isApplicationInForeground()) {
        mNotificationManager.cancel(mNotificationModel.getStopwatchNotificationId());
        return;
    }

    @StringRes
    final int eventLabel = R.string.label_notification;

    // Intent to load the app when the notification is tapped.
    final Intent showApp = new Intent(mContext, HandleDeskClockApiCalls.class)
            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).setAction(HandleDeskClockApiCalls.ACTION_SHOW_STOPWATCH)
            .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);

    final PendingIntent pendingShowApp = PendingIntent.getActivity(mContext, 0, showApp,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

    // Compute some values required below.
    final boolean running = stopwatch.isRunning();
    final String pname = mContext.getPackageName();
    final Resources res = mContext.getResources();
    final long base = SystemClock.elapsedRealtime() - stopwatch.getTotalTime();

    final RemoteViews collapsed = new RemoteViews(pname, R.layout.stopwatch_notif_collapsed);
    collapsed.setChronometer(R.id.swn_collapsed_chronometer, base, null, running);
    collapsed.setOnClickPendingIntent(R.id.swn_collapsed_hitspace, pendingShowApp);
    collapsed.setImageViewResource(R.id.notification_icon, R.drawable.stat_notify_stopwatch);

    final RemoteViews expanded = new RemoteViews(pname, R.layout.stopwatch_notif_expanded);
    expanded.setChronometer(R.id.swn_expanded_chronometer, base, null, running);
    expanded.setOnClickPendingIntent(R.id.swn_expanded_hitspace, pendingShowApp);
    expanded.setImageViewResource(R.id.notification_icon, R.drawable.stat_notify_stopwatch);

    @IdRes
    final int leftButtonId = R.id.swn_left_button;
    @IdRes
    final int rightButtonId = R.id.swn_right_button;
    if (running) {
        // Left button: Pause
        expanded.setTextViewText(leftButtonId, res.getText(R.string.sw_pause_button));
        //            setTextViewDrawable(expanded, leftButtonId, R.drawable.ic_pause_24dp);
        final Intent pause = new Intent(mContext, StopwatchService.class)
                .setAction(HandleDeskClockApiCalls.ACTION_PAUSE_STOPWATCH)
                .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);
        expanded.setOnClickPendingIntent(leftButtonId, pendingServiceIntent(pause));

        // Right button: Add Lap
        if (canAddMoreLaps()) {
            expanded.setTextViewText(rightButtonId, res.getText(R.string.sw_lap_button));
            //                setTextViewDrawable(expanded, rightButtonId, R.drawable.ic_sw_lap_24dp);

            final Intent lap = new Intent(mContext, StopwatchService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_LAP_STOPWATCH)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);
            expanded.setOnClickPendingIntent(rightButtonId, pendingServiceIntent(lap));
            expanded.setViewVisibility(rightButtonId, VISIBLE);
        } else {
            expanded.setViewVisibility(rightButtonId, INVISIBLE);
        }

        // Show the current lap number if any laps have been recorded.
        final int lapCount = getLaps().size();
        if (lapCount > 0) {
            final int lapNumber = lapCount + 1;
            final String lap = res.getString(R.string.sw_notification_lap_number, lapNumber);
            collapsed.setTextViewText(R.id.swn_collapsed_laps, lap);
            collapsed.setViewVisibility(R.id.swn_collapsed_laps, VISIBLE);
            expanded.setTextViewText(R.id.swn_expanded_laps, lap);
            expanded.setViewVisibility(R.id.swn_expanded_laps, VISIBLE);
        } else {
            collapsed.setViewVisibility(R.id.swn_collapsed_laps, GONE);
            expanded.setViewVisibility(R.id.swn_expanded_laps, GONE);
        }
    } else {
        // Left button: Start
        expanded.setTextViewText(leftButtonId, res.getText(R.string.sw_start_button));
        //            setTextViewDrawable(expanded, leftButtonId, R.drawable.ic_start_24dp);
        final Intent start = new Intent(mContext, StopwatchService.class)
                .setAction(HandleDeskClockApiCalls.ACTION_START_STOPWATCH)
                .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);
        expanded.setOnClickPendingIntent(leftButtonId, pendingServiceIntent(start));

        // Right button: Reset (HandleDeskClockApiCalls will also bring forward the app)
        expanded.setViewVisibility(rightButtonId, VISIBLE);
        expanded.setTextViewText(rightButtonId, res.getText(R.string.sw_reset_button));
        //            setTextViewDrawable(expanded, rightButtonId, R.drawable.ic_reset_24dp);
        final Intent reset = new Intent(mContext, HandleDeskClockApiCalls.class)
                .setAction(HandleDeskClockApiCalls.ACTION_RESET_STOPWATCH)
                .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);
        expanded.setOnClickPendingIntent(rightButtonId, pendingActivityIntent(reset));

        // Indicate the stopwatch is paused.
        collapsed.setTextViewText(R.id.swn_collapsed_laps, res.getString(R.string.swn_paused));
        collapsed.setViewVisibility(R.id.swn_collapsed_laps, VISIBLE);
        expanded.setTextViewText(R.id.swn_expanded_laps, res.getString(R.string.swn_paused));
        expanded.setViewVisibility(R.id.swn_expanded_laps, VISIBLE);
    }

    // Swipe away will reset the stopwatch without bringing forward the app.
    final Intent reset = new Intent(mContext, StopwatchService.class)
            .setAction(HandleDeskClockApiCalls.ACTION_RESET_STOPWATCH)
            .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);

    final Notification notification = new NotificationCompat.Builder(mContext).setLocalOnly(true)
            .setOngoing(running).setContent(collapsed).setAutoCancel(stopwatch.isPaused())
            .setPriority(Notification.PRIORITY_MAX).setDeleteIntent(pendingServiceIntent(reset))
            .setSmallIcon(R.drawable.ic_tab_stopwatch_activated).build();
    if (Build.VERSION.SDK_INT >= 16) {
        notification.bigContentView = expanded;
    }
    mNotificationManager.notify(mNotificationModel.getStopwatchNotificationId(), notification);
}

From source file:de.ub0r.android.portaltimer.UpdateReceiver.java

private void schedNext(final Context context) {
    Log.d(TAG, "schedNext()");
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Log.d(TAG, "current: " + mNow);
    long t;// ww w.j a  v a2 s .co m
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    if (pm.isScreenOn()) {
        t = mNow + 1000L;
    } else {
        t = mNextTarget - mNow;
        Log.d(TAG, "t: " + t);
        if (t < 0) { // IllegalState?
            t = 30000;
        } else if (t < 30000) {
            t = 5000;
        } else if (t < 60000) {
            t = 15000;
        } else {
            t = 30000;
        }
        Log.d(TAG, "t: " + t);
        long diff = mNextTarget - (mNow + t);
        diff = (diff / 5000) * 5000;
        Log.d(TAG, "diff: " + diff);
        if (diff == 0) {
            t = mNow + 5000;
        } else {
            t = mNextTarget - diff - 1000;
        }
    }
    Log.d(TAG, "next: " + t);
    long et;
    if (t - System.currentTimeMillis() < 100) { // IllegalState?
        et = 1000 + SystemClock.elapsedRealtime();
    } else {
        et = t - System.currentTimeMillis() + SystemClock.elapsedRealtime();
    }
    am.set(AlarmManager.ELAPSED_REALTIME, et, PendingIntent.getBroadcast(context, 0,
            new Intent(context, UpdateReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT));
}

From source file:com.google.android.apps.mytracks.widgets.TrackWidgetProvider.java

/**
 * Updates total time./* w ww .  j  av a2  s.  com*/
 * 
 * @param remoteViews the remote views
 * @param tripStatistics the trip statistics
 * @param isRecording true if recording
 * @param recordingTrackPaused true if recording track is paused
 */
private void updateTotalTime(RemoteViews remoteViews, TripStatistics tripStatistics, boolean isRecording,
        boolean recordingTrackPaused) {
    long totalTime;
    if (tripStatistics == null) {
        totalTime = 0L;
    } else {
        totalTime = tripStatistics.getTotalTime();
        if (isRecording && !recordingTrackPaused) {
            totalTime += System.currentTimeMillis() - tripStatistics.getStopTime();
        }
    }
    remoteViews.setChronometer(R.id.track_widget_total_time_value, SystemClock.elapsedRealtime() - totalTime,
            null, isRecording && !recordingTrackPaused);
}

From source file:com.android.deskclock.data.StopwatchModel.java

/**
 * Updates the notification to reflect the latest state of the stopwatch and recorded laps.
 *///  w  w w  . j a v  a 2  s. c o  m
void updateNotification() {
    final Stopwatch stopwatch = getStopwatch();

    // Notification should be hidden if the stopwatch has no time or the app is open.
    if (stopwatch.isReset() || mNotificationModel.isApplicationInForeground()) {
        mNotificationManager.cancel(mNotificationModel.getStopwatchNotificationId());
        return;
    }

    @StringRes
    final int eventLabel = R.string.label_notification;

    // Intent to load the app when the notification is tapped.
    final Intent showApp = new Intent(mContext, HandleDeskClockApiCalls.class)
            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).setAction(HandleDeskClockApiCalls.ACTION_SHOW_STOPWATCH)
            .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);

    final PendingIntent pendingShowApp = PendingIntent.getActivity(mContext, 0, showApp,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

    // Compute some values required below.
    final boolean running = stopwatch.isRunning();
    final String pname = mContext.getPackageName();
    final Resources res = mContext.getResources();
    final long base = SystemClock.elapsedRealtime() - stopwatch.getTotalTime();

    final RemoteViews collapsed = new RemoteViews(pname, R.layout.stopwatch_notif_collapsed);
    collapsed.setChronometer(R.id.swn_collapsed_chronometer, base, null, running);
    collapsed.setOnClickPendingIntent(R.id.swn_collapsed_hitspace, pendingShowApp);
    collapsed.setImageViewResource(R.id.notification_icon, R.drawable.stat_notify_stopwatch);

    final RemoteViews expanded = new RemoteViews(pname, R.layout.stopwatch_notif_expanded);
    expanded.setChronometer(R.id.swn_expanded_chronometer, base, null, running);
    expanded.setOnClickPendingIntent(R.id.swn_expanded_hitspace, pendingShowApp);
    expanded.setImageViewResource(R.id.notification_icon, R.drawable.stat_notify_stopwatch);

    @IdRes
    final int leftButtonId = R.id.swn_left_button;
    @IdRes
    final int rightButtonId = R.id.swn_right_button;
    if (running) {
        // Left button: Pause
        expanded.setTextViewText(leftButtonId, res.getText(R.string.sw_pause_button));
        setTextViewDrawable(expanded, leftButtonId, R.drawable.ic_pause_24dp);
        final Intent pause = new Intent(mContext, StopwatchService.class)
                .setAction(HandleDeskClockApiCalls.ACTION_PAUSE_STOPWATCH)
                .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);
        expanded.setOnClickPendingIntent(leftButtonId, pendingServiceIntent(pause));

        // Right button: Add Lap
        if (canAddMoreLaps()) {
            expanded.setTextViewText(rightButtonId, res.getText(R.string.sw_lap_button));
            setTextViewDrawable(expanded, rightButtonId, R.drawable.ic_sw_lap_24dp);

            final Intent lap = new Intent(mContext, StopwatchService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_LAP_STOPWATCH)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);
            expanded.setOnClickPendingIntent(rightButtonId, pendingServiceIntent(lap));
            expanded.setViewVisibility(rightButtonId, VISIBLE);
        } else {
            expanded.setViewVisibility(rightButtonId, INVISIBLE);
        }

        // Show the current lap number if any laps have been recorded.
        final int lapCount = getLaps().size();
        if (lapCount > 0) {
            final int lapNumber = lapCount + 1;
            final String lap = res.getString(R.string.sw_notification_lap_number, lapNumber);
            collapsed.setTextViewText(R.id.swn_collapsed_laps, lap);
            collapsed.setViewVisibility(R.id.swn_collapsed_laps, VISIBLE);
            expanded.setTextViewText(R.id.swn_expanded_laps, lap);
            expanded.setViewVisibility(R.id.swn_expanded_laps, VISIBLE);
        } else {
            collapsed.setViewVisibility(R.id.swn_collapsed_laps, GONE);
            expanded.setViewVisibility(R.id.swn_expanded_laps, GONE);
        }
    } else {
        // Left button: Start
        expanded.setTextViewText(leftButtonId, res.getText(R.string.sw_start_button));
        setTextViewDrawable(expanded, leftButtonId, R.drawable.ic_start_24dp);
        final Intent start = new Intent(mContext, StopwatchService.class)
                .setAction(HandleDeskClockApiCalls.ACTION_START_STOPWATCH)
                .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);
        expanded.setOnClickPendingIntent(leftButtonId, pendingServiceIntent(start));

        // Right button: Reset (HandleDeskClockApiCalls will also bring forward the app)
        expanded.setViewVisibility(rightButtonId, VISIBLE);
        expanded.setTextViewText(rightButtonId, res.getText(R.string.sw_reset_button));
        setTextViewDrawable(expanded, rightButtonId, R.drawable.ic_reset_24dp);
        final Intent reset = new Intent(mContext, HandleDeskClockApiCalls.class)
                .setAction(HandleDeskClockApiCalls.ACTION_RESET_STOPWATCH)
                .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);
        expanded.setOnClickPendingIntent(rightButtonId, pendingActivityIntent(reset));

        // Indicate the stopwatch is paused.
        collapsed.setTextViewText(R.id.swn_collapsed_laps, res.getString(R.string.swn_paused));
        collapsed.setViewVisibility(R.id.swn_collapsed_laps, VISIBLE);
        expanded.setTextViewText(R.id.swn_expanded_laps, res.getString(R.string.swn_paused));
        expanded.setViewVisibility(R.id.swn_expanded_laps, VISIBLE);
    }

    // Swipe away will reset the stopwatch without bringing forward the app.
    final Intent reset = new Intent(mContext, StopwatchService.class)
            .setAction(HandleDeskClockApiCalls.ACTION_RESET_STOPWATCH)
            .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);

    final Notification notification = new NotificationCompat.Builder(mContext).setLocalOnly(true)
            .setOngoing(running).setContent(collapsed).setAutoCancel(stopwatch.isPaused())
            .setPriority(Notification.PRIORITY_MAX).setDeleteIntent(pendingServiceIntent(reset))
            .setSmallIcon(R.drawable.ic_tab_stopwatch_activated).build();
    notification.bigContentView = expanded;
    mNotificationManager.notify(mNotificationModel.getStopwatchNotificationId(), notification);
}

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.jav a  2  s .  c  o m*/
 */
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);
}