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:com.tingtingapps.securesms.service.KeyCachingService.java

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

    if ((activitiesRunning == 0) && (KeyCachingService.masterSecret != null) && timeoutEnabled
            && !TextSecurePreferences.isPasswordDisabled(this)) {
        long timeoutMinutes = TextSecurePreferences.getPassphraseTimeoutInterval(this);
        long timeoutMillis = TimeUnit.MINUTES.toMillis(timeoutMinutes);

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

        AlarmManager alarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE);
        alarmManager.cancel(pending);/*from   w  w w. j  a v  a2s.c o  m*/
        alarmManager.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + timeoutMillis, pending);
    }
}

From source file:com.achep.acdisplay.services.activemode.ActiveModeService.java

private void pingConsumingSensorsInternal() {
    // Find maximum remaining time.
    int remainingTime = -1;
    for (ActiveModeSensor ams : mSensors) {
        if (ams.isAttached() && ams instanceof ActiveModeSensor.Consuming) {
            ActiveModeSensor.Consuming sensor = (ActiveModeSensor.Consuming) ams;
            remainingTime = Math.max(remainingTime, sensor.getRemainingTime());
        }//from w w w. j  av a 2 s . c o  m
    }

    long now = SystemClock.elapsedRealtime();
    int delta = (int) (now - mConsumingPingTimestamp);

    remainingTime -= delta;
    if (remainingTime < 0) {
        return; // Too late
    }

    // Acquire wake lock to be sure that sensors will be fine.
    releaseWakeLock();
    PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKE_LOCK_TAG);
    mWakeLock.acquire(remainingTime);

    // Ping sensors
    for (ActiveModeSensor ams : mSensors) {
        if (ams.isAttached() && ams instanceof ActiveModeSensor.Consuming) {
            ActiveModeSensor.Consuming sensor = (ActiveModeSensor.Consuming) ams;

            int sensorRemainingTime = sensor.getRemainingTime() - delta;
            if (sensorRemainingTime > 0) {
                sensor.ping(sensorRemainingTime);
            }
        }
    }
}

From source file:edu.princeton.jrpalmer.asmlibrary.Settings.java

@Override
protected void onResume() {

    if (Util.trafficCop(this))
        finish();/* ww w  .  j av a  2 s. c o m*/
    IntentFilter uploadFilter;
    uploadFilter = new IntentFilter(
            getResources().getString(R.string.internal_message_id) + Util.MESSAGE_FIX_UPLOADED);
    uploadReceiver = new UploadReceiver();
    registerReceiver(uploadReceiver, uploadFilter);

    IntentFilter fixFilter;
    fixFilter = new IntentFilter(
            getResources().getString(R.string.internal_message_id) + Util.MESSAGE_FIX_RECORDED);
    fixReceiver = new FixReceiver();
    registerReceiver(fixReceiver, fixFilter);

    shareMyData = PropertyHolder.getShareData();

    toggleParticipationViews(shareMyData);

    int nUploads = PropertyHolder.getNUploads();

    final long participationTime = PropertyHolder.ptCheck();
    participationTimeText.setBase(SystemClock.elapsedRealtime() - participationTime);

    // service button
    boolean isServiceOn = PropertyHolder.isServiceOn();

    mServiceButton.setChecked(isServiceOn);
    mServiceButton.setOnClickListener(new ToggleButton.OnClickListener() {
        public void onClick(View view) {
            if (view.getId() != R.id.service_button)
                return;
            Context context = view.getContext();
            boolean on = ((ToggleButton) view).isChecked();
            String schedule = on ? Util.MESSAGE_SCHEDULE : Util.MESSAGE_UNSCHEDULE;
            // Log.e(TAG, schedule + on);

            // now schedule or unschedule
            Intent intent = new Intent(getString(R.string.internal_message_id) + schedule);
            context.sendBroadcast(intent);
            showSpinner(on, storeMyData);

            if (on && shareMyData) {
                final long ptNow = PropertyHolder.ptStart();
                participationTimeText.setBase(SystemClock.elapsedRealtime() - ptNow);
                participationTimeText.start();

                ContentResolver ucr = getContentResolver();

                ucr.insert(Util.getUploadQueueUri(context), UploadContentValues.createUpload("ONF",
                        "on," + Util.iso8601(System.currentTimeMillis()) + "," + ptNow));
            } else {

                final long ptNow = PropertyHolder.ptStop();
                participationTimeText.setBase(SystemClock.elapsedRealtime() - ptNow);
                participationTimeText.stop();
                // stop uploader
                Intent stopUploaderIntent = new Intent(Settings.this, FileUploader.class);
                // Stop service if it is currently running
                stopService(stopUploaderIntent);

                if (shareMyData) {

                    ContentResolver ucr = getContentResolver();

                    ucr.insert(Util.getUploadQueueUri(context), UploadContentValues.createUpload("ONF",
                            "off," + Util.iso8601(System.currentTimeMillis()) + "," + ptNow));

                }

            }
            // If user turns CountdownDisplay on but GPS is not on, remind
            // user to turn
            // GPS on
            if (on) {
                final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

                if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                    if (!manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                        buildAlertMessageNoGpsNoNet();
                    } else
                        buildAlertMessageNoGps();
                }
            }

            return;
        }
    });

    // interval spinner
    int intspinner_item = android.R.layout.simple_spinner_item;
    int dropdown_item = android.R.layout.simple_spinner_dropdown_item;
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.interval_array,
            intspinner_item);
    adapter.setDropDownViewResource(dropdown_item);
    mIntervalSpinner.setAdapter(adapter);
    mIntervalSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
            int parentId = parent.getId();
            if (parentId != R.id.spinner_interval)
                return;
            if (pos > mInterval.length)
                return;
            if (!PropertyHolder.isServiceOn()) {
                PropertyHolder.setAlarmInterval(mInterval[pos]);
                return;
            }
            PropertyHolder.setAlarmInterval(mInterval[pos]);
            mServiceButton.setChecked(true);

            Intent intent = new Intent(getString(R.string.internal_message_id) + Util.MESSAGE_SCHEDULE);
            Context context = getApplicationContext();
            context.sendBroadcast(intent);
            showSpinner(true, storeMyData);

            if (shareMyData) {
                ContentResolver ucr = getContentResolver();

                ucr.insert(Util.getUploadQueueUri(context), UploadContentValues.createUpload("INT",
                        Util.iso8601(System.currentTimeMillis()) + "," + mInterval[pos]));
            }
        }

        public void onNothingSelected(AdapterView<?> parent) {
            // do nothing
        }
    });
    int pos = ai2pos(PropertyHolder.getAlarmInterval());
    mIntervalSpinner.setSelection(pos);
    showSpinner(isServiceOn, storeMyData);

    // mydata buttons

    // storage spinner

    storageDays = PropertyHolder.getStorageDays();

    mStorageSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
            int parentId = parent.getId();
            if (parentId != R.id.spinner_mydata)
                return;
            if (pos > MAX_STORAGE - MIN_STORAGE)
                return;
            PropertyHolder.setStorageDays(pos + MIN_STORAGE);
            PropertyHolder.setStoreMyData((pos + MIN_STORAGE) > 0);
        }

        public void onNothingSelected(AdapterView<?> parent) {
            // do nothing
        }
    });
    int storagepos = storageDays - MIN_STORAGE;
    mStorageSpinner.setSelection(storagepos);

    // NEW STUFF
    mToggleSatRadioGroup = (RadioGroup) findViewById(R.id.toggleSatRadioGroup);
    mToggleIconsRadioGroup = (RadioGroup) findViewById(R.id.toggleIconsRadioGroup);
    mToggleAccRadioGroup = (RadioGroup) findViewById(R.id.toggleAccRadioGroup);
    mLimitStartDateRadioGroup = (RadioGroup) findViewById(R.id.limitStartDateRadioGroup);
    mLimitEndDateRadioGroup = (RadioGroup) findViewById(R.id.limitEndDateRadioGroup);

    Intent i = getIntent();
    if (i.getBooleanExtra(MapMyData.DATES_BUTTON_MESSAGE, false)) {

        RelativeLayout dateSettingsArea = (RelativeLayout) findViewById(R.id.dateSettingsArea);
        dateSettingsArea.setFocusable(true);
        dateSettingsArea.setFocusableInTouchMode(true);
        dateSettingsArea.requestFocus();
    }

    if (shareMyData && isServiceOn) {
        participationTimeText.setBase(SystemClock.elapsedRealtime() - PropertyHolder.ptStart());
        participationTimeText.start();
    }

    nUploadsText.setText(String.valueOf(nUploads));

    if (nUploads >= Util.UPLOADS_TO_PRO && !PropertyHolder.getProVersion()
            && participationTime >= Util.TIME_TO_PRO) {
        Util.createProNotification(context);
        PropertyHolder.setProVersion(true);
        PropertyHolder.setNeedsDebriefingSurvey(true);
    }

    boolean proV = PropertyHolder.getProVersion();

    // 19 December 2013: end of research changes
    mShareDataRadioGroup.check(R.id.sharedataNo);

    mShareDataRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == R.id.sharedataYes) {
                buildSharingOverAnnouncement();
            }
            mShareDataRadioGroup.check(R.id.sharedataNo);
        }
    });

    /*
     * if (proV) {
     * 
     * if (shareMyData) { mShareDataRadioGroup.check(R.id.sharedataYes); if
     * (PropertyHolder.isRegistered() == false ||
     * PropertyHolder.hasConsented() == false) { send2Intro(context); } }
     * else { mShareDataRadioGroup.check(R.id.sharedataNo); }
     * 
     * mShareDataRadioGroup .setOnCheckedChangeListener(new
     * OnCheckedChangeListener() {
     * 
     * @Override public void onCheckedChanged(RadioGroup group, int
     * checkedId) { shareMyData = (checkedId == R.id.sharedataYes);
     * PropertyHolder.setShareData(shareMyData);
     * toggleParticipationViews(shareMyData); final boolean on =
     * PropertyHolder.isServiceOn(); if (shareMyData) { if
     * (PropertyHolder.isRegistered() == false ||
     * PropertyHolder.hasConsented() == false) { send2Intro(context);
     * 
     * } if (on) {
     * 
     * final long ptNow = PropertyHolder.ptStart();
     * participationTimeText.setBase(SystemClock .elapsedRealtime() -
     * ptNow);
     * 
     * participationTimeText.start();
     * 
     * ContentResolver ucr = getContentResolver();
     * 
     * ucr.insert( Util.getUploadQueueUri(context),
     * UploadContentValues.createUpload( "ONF", "on," + Util.iso8601(System
     * .currentTimeMillis()) + "," + ptNow));
     * 
     * } } else {
     * 
     * final long ptNow = PropertyHolder.ptStop();
     * participationTimeText.setBase(SystemClock .elapsedRealtime() -
     * ptNow); participationTimeText.stop(); // stop uploader Intent i = new
     * Intent(Settings.this, FileUploader.class); // Stop service if it is
     * currently running stopService(i);
     * 
     * if (on) { ContentResolver ucr = getContentResolver();
     * 
     * ucr.insert( Util.getUploadQueueUri(context),
     * UploadContentValues.createUpload( "ONF", "off," + Util.iso8601(System
     * .currentTimeMillis()) + "," + ptNow));
     * 
     * }
     * 
     * }
     * 
     * } }); } else { mShareDataRadioGroup.check(R.id.sharedataYes);
     * mShareDataRadioGroup .setOnCheckedChangeListener(new
     * OnCheckedChangeListener() {
     * 
     * @Override public void onCheckedChanged(RadioGroup group, int
     * checkedId) { if (checkedId == R.id.sharedataNo) {
     * mShareDataRadioGroup.check(R.id.sharedataYes);
     * showCurrentlySharingDialog(); } } });
     * 
     * }
     */
    new CheckPendingUploadsSizeTask().execute(context);
    new CheckUserDbSizeTask().execute(context);

    deletePendingUploadsButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            ContentResolver cr = getContentResolver();
            final int nDeleted = cr.delete(Util.getUploadQueueUri(context), "1", null);

            // Log.i("Settings", "number of rows deleted=" + nDeleted);
            Util.toast(context, String.valueOf(nDeleted) + " "
                    + getResources().getString(R.string.locations_deleted) + ".");

            updateStorageSizes();

        }

    });

    deleteUserDbButton = (ImageButton) findViewById(R.id.deleteMyDbButton);

    deleteUserDbButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            ContentResolver cr = getContentResolver();
            final int nDeleted = cr.delete(Util.getFixesUri(context), "1", null);

            Util.toast(context, String.valueOf(nDeleted) + " "
                    + getResources().getString(R.string.locations_deleted) + ".");
            updateStorageSizes();

        }

    });

    uploadButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            if (Util.isOnline(context)) {
                Intent i = new Intent(Settings.this, FileUploader.class);
                startService(i);

                new UploadMessageTask().execute(context);
            } else {
                Util.toast(context, getResources().getString(R.string.offline_warning));
            }

        }

    });

    mToggleSatRadioGroup.check(PropertyHolder.getMapSat() ? R.id.toggleSatYes : R.id.toggleSatNo);

    mToggleSatRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            PropertyHolder.setMapSat(checkedId == R.id.toggleSatYes);
        }
    });

    mToggleIconsRadioGroup.check(PropertyHolder.getMapIcons() ? R.id.toggleIconsYes : R.id.toggleIconsNo);

    mToggleIconsRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            PropertyHolder.setMapIcons(checkedId == R.id.toggleIconsYes);
        }
    });

    mToggleAccRadioGroup.check(PropertyHolder.getMapAcc() ? R.id.toggleAccYes : R.id.toggleAccNo);

    mToggleAccRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            PropertyHolder.setMapAcc(checkedId == R.id.toggleAccYes);
        }
    });

    mStartDateButton = (Button) findViewById(R.id.startDateButton);
    mEndDateButton = (Button) findViewById(R.id.endDateButton);

    boolean limitStartDate = PropertyHolder.getLimitStartDate();
    boolean limitEndDate = PropertyHolder.getLimitEndDate();

    if (!limitStartDate)
        mStartDateButton.setVisibility(View.GONE);
    else {
        mStartDateButton.setVisibility(View.VISIBLE);

    }
    if (!limitEndDate)
        mEndDateButton.setVisibility(View.GONE);
    else {
        mEndDateButton.setVisibility(View.VISIBLE);
    }

    mLimitStartDateRadioGroup.check(limitStartDate ? R.id.limitStartDateYes : R.id.limitStartDateNo);

    mLimitStartDateRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            PropertyHolder.setLimitStartDate(checkedId == R.id.limitStartDateYes);

            if (checkedId != R.id.limitStartDateYes)
                mStartDateButton.setVisibility(View.GONE);
            else {
                mStartDateButton.setVisibility(View.VISIBLE);
            }
        }
    });

    mLimitEndDateRadioGroup.check(limitEndDate ? R.id.limitEndDateYes : R.id.limitEndDateNo);

    mLimitEndDateRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            PropertyHolder.setLimitEndDate(checkedId == R.id.limitEndDateYes);

            if (checkedId != R.id.limitEndDateYes)
                mEndDateButton.setVisibility(View.GONE);
            else {
                mEndDateButton.setVisibility(View.VISIBLE);
            }
        }
    });

    mStartDateButton.setText(Util.userDateNoTime(PropertyHolder.getMapStartDate()));
    mStartDateButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            DialogFragment newFragment = new StartDatePickerFragment();
            newFragment.show(getSupportFragmentManager(), "datePicker");

        }

    });

    mEndDateButton.setText(Util.userDateNoTime(PropertyHolder.getMapEndDate()));
    mEndDateButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            DialogFragment newFragment = new EndDatePickerFragment();
            newFragment.show(getSupportFragmentManager(), "datePicker");

        }

    });

    if (PropertyHolder.getNeedsDebriefingSurvey()) {
        buildProAnnouncement();
        PropertyHolder.setNeedsDebriefingSurvey(false);
    }

    super.onResume();

}

From source file:com.kercer.kernet.http.KCNetworkBasic.java

protected void logError(String what, String url, long start) {
    long now = SystemClock.elapsedRealtime();
    KCLog.v("HTTP ERROR(%s) %d ms to fetch %s", what, (now - start), url);
}

From source file:com.android.quake.llvm.DownloaderActivity.java

private void onReportProgress(int progress) {
    mProgress.setText(mPercentFormat.format(progress / 10000.0));
    long now = SystemClock.elapsedRealtime();
    if (mStartTime == 0) {
        mStartTime = now;/*from  w w w . ja v  a2  s. co m*/
    }
    long delta = now - mStartTime;
    String timeRemaining = getString(R.string.download_activity_time_remaining_unknown);
    if ((delta > 3 * MS_PER_SECOND) && (progress > 100)) {
        long totalTime = 10000 * delta / progress;
        long timeLeft = Math.max(0L, totalTime - delta);
        if (timeLeft > MS_PER_DAY) {
            timeRemaining = Long.toString((timeLeft + MS_PER_DAY - 1) / MS_PER_DAY) + " "
                    + getString(R.string.download_activity_time_remaining_days);
        } else if (timeLeft > MS_PER_HOUR) {
            timeRemaining = Long.toString((timeLeft + MS_PER_HOUR - 1) / MS_PER_HOUR) + " "
                    + getString(R.string.download_activity_time_remaining_hours);
        } else if (timeLeft > MS_PER_MINUTE) {
            timeRemaining = Long.toString((timeLeft + MS_PER_MINUTE - 1) / MS_PER_MINUTE) + " "
                    + getString(R.string.download_activity_time_remaining_minutes);
        } else {
            timeRemaining = Long.toString((timeLeft + MS_PER_SECOND - 1) / MS_PER_SECOND) + " "
                    + getString(R.string.download_activity_time_remaining_seconds);
        }
    }
    mTimeRemaining.setText(timeRemaining);
}

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  ww.  j a v a2s . 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:com.androidinspain.deskclock.data.TimerNotificationBuilder.java

public Notification build(Context context, NotificationModel nm, List<Timer> unexpired) {
    final Timer timer = unexpired.get(0);
    final int count = unexpired.size();

    // Compute some values required below.
    final boolean running = timer.isRunning();
    final Resources res = context.getResources();

    final long base = getChronometerBase(timer);
    final String pname = context.getPackageName();

    final List<Action> actions = new ArrayList<>(2);

    final CharSequence stateText;
    if (count == 1) {
        if (running) {
            // Single timer is running.
            if (TextUtils.isEmpty(timer.getLabel())) {
                stateText = res.getString(com.androidinspain.deskclock.R.string.timer_notification_label);
            } else {
                stateText = timer.getLabel();
            }//from   w  w  w  .  j  ava  2s.  c  om

            // Left button: Pause
            final Intent pause = new Intent(context, TimerService.class)
                    .setAction(TimerService.ACTION_PAUSE_TIMER)
                    .putExtra(TimerService.EXTRA_TIMER_ID, timer.getId());

            @DrawableRes
            final int icon1 = com.androidinspain.deskclock.R.drawable.ic_pause_24dp;
            final CharSequence title1 = res.getText(com.androidinspain.deskclock.R.string.timer_pause);
            final PendingIntent intent1 = Utils.pendingServiceIntent(context, pause);
            actions.add(new Action.Builder(icon1, title1, intent1).build());

            // Right Button: +1 Minute
            final Intent addMinute = new Intent(context, TimerService.class)
                    .setAction(TimerService.ACTION_ADD_MINUTE_TIMER)
                    .putExtra(TimerService.EXTRA_TIMER_ID, timer.getId());

            @DrawableRes
            final int icon2 = com.androidinspain.deskclock.R.drawable.ic_add_24dp;
            final CharSequence title2 = res.getText(com.androidinspain.deskclock.R.string.timer_plus_1_min);
            final PendingIntent intent2 = Utils.pendingServiceIntent(context, addMinute);
            actions.add(new Action.Builder(icon2, title2, intent2).build());

        } else {
            // Single timer is paused.
            stateText = res.getString(com.androidinspain.deskclock.R.string.timer_paused);

            // Left button: Start
            final Intent start = new Intent(context, TimerService.class)
                    .setAction(TimerService.ACTION_START_TIMER)
                    .putExtra(TimerService.EXTRA_TIMER_ID, timer.getId());

            @DrawableRes
            final int icon1 = com.androidinspain.deskclock.R.drawable.ic_start_24dp;
            final CharSequence title1 = res.getText(com.androidinspain.deskclock.R.string.sw_resume_button);
            final PendingIntent intent1 = Utils.pendingServiceIntent(context, start);
            actions.add(new Action.Builder(icon1, title1, intent1).build());

            // Right Button: Reset
            final Intent reset = new Intent(context, TimerService.class)
                    .setAction(TimerService.ACTION_RESET_TIMER)
                    .putExtra(TimerService.EXTRA_TIMER_ID, timer.getId());

            @DrawableRes
            final int icon2 = com.androidinspain.deskclock.R.drawable.ic_reset_24dp;
            final CharSequence title2 = res.getText(com.androidinspain.deskclock.R.string.sw_reset_button);
            final PendingIntent intent2 = Utils.pendingServiceIntent(context, reset);
            actions.add(new Action.Builder(icon2, title2, intent2).build());
        }
    } else {
        if (running) {
            // At least one timer is running.
            stateText = res.getString(com.androidinspain.deskclock.R.string.timers_in_use, count);
        } else {
            // All timers are paused.
            stateText = res.getString(com.androidinspain.deskclock.R.string.timers_stopped, count);
        }

        final Intent reset = TimerService.createResetUnexpiredTimersIntent(context);

        @DrawableRes
        final int icon1 = com.androidinspain.deskclock.R.drawable.ic_reset_24dp;
        final CharSequence title1 = res.getText(com.androidinspain.deskclock.R.string.timer_reset_all);
        final PendingIntent intent1 = Utils.pendingServiceIntent(context, reset);
        actions.add(new Action.Builder(icon1, title1, intent1).build());
    }

    // Intent to load the app and show the timer when the notification is tapped.
    final Intent showApp = new Intent(context, TimerService.class).setAction(TimerService.ACTION_SHOW_TIMER)
            .putExtra(TimerService.EXTRA_TIMER_ID, timer.getId())
            .putExtra(Events.EXTRA_EVENT_LABEL, com.androidinspain.deskclock.R.string.label_notification);

    final PendingIntent pendingShowApp = PendingIntent.getService(context, REQUEST_CODE_UPCOMING, showApp,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

    final Builder notification = new NotificationCompat.Builder(context).setOngoing(true).setLocalOnly(true)
            .setShowWhen(false).setAutoCancel(false).setContentIntent(pendingShowApp)
            .setPriority(Notification.PRIORITY_HIGH).setCategory(NotificationCompat.CATEGORY_ALARM)
            .setSmallIcon(com.androidinspain.deskclock.R.drawable.stat_notify_timer)
            .setSortKey(nm.getTimerNotificationSortKey()).setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setStyle(new NotificationCompat.DecoratedCustomViewStyle())
            .setColor(ContextCompat.getColor(context, com.androidinspain.deskclock.R.color.default_background));

    for (Action action : actions) {
        notification.addAction(action);
    }

    if (Utils.isNOrLater()) {
        notification.setCustomContentView(buildChronometer(pname, base, running, stateText))
                .setGroup(nm.getTimerNotificationGroupKey());
    } else {
        final CharSequence contentTextPreN;
        if (count == 1) {
            contentTextPreN = TimerStringFormatter.formatTimeRemaining(context, timer.getRemainingTime(),
                    false);
        } else if (running) {
            final String timeRemaining = TimerStringFormatter.formatTimeRemaining(context,
                    timer.getRemainingTime(), false);
            contentTextPreN = context.getString(com.androidinspain.deskclock.R.string.next_timer_notif,
                    timeRemaining);
        } else {
            contentTextPreN = context.getString(com.androidinspain.deskclock.R.string.all_timers_stopped_notif);
        }

        notification.setContentTitle(stateText).setContentText(contentTextPreN);

        final AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        final Intent updateNotification = TimerService.createUpdateNotificationIntent(context);
        final long remainingTime = timer.getRemainingTime();
        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, REQUEST_CODE_UPCOMING,
                    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 notification.build();
}

From source file:android.support.v7.app.NotificationCompatImplBase.java

private static RemoteViews applyStandardTemplate(Context context, CharSequence contentTitle,
        CharSequence contentText, CharSequence contentInfo, int number, Bitmap largeIcon, CharSequence subText,
        boolean useChronometer, long when, int resId, boolean fitIn1U) {
    RemoteViews contentView = new RemoteViews(context.getPackageName(), resId);
    boolean showLine3 = false;
    boolean showLine2 = false;

    // On versions before Jellybean, the large icon was shown by SystemUI, so we need to hide
    // it here.//from w w w  .  j  a  va2s . c  o  m
    if (largeIcon != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        contentView.setViewVisibility(R.id.icon, View.VISIBLE);
        contentView.setImageViewBitmap(R.id.icon, largeIcon);
    } else {
        contentView.setViewVisibility(R.id.icon, View.GONE);
    }
    if (contentTitle != null) {
        contentView.setTextViewText(R.id.title, contentTitle);
    }
    if (contentText != null) {
        contentView.setTextViewText(R.id.text, contentText);
        showLine3 = true;
    }
    if (contentInfo != null) {
        contentView.setTextViewText(R.id.info, contentInfo);
        contentView.setViewVisibility(R.id.info, View.VISIBLE);
        showLine3 = true;
    } else if (number > 0) {
        final int tooBig = context.getResources().getInteger(R.integer.status_bar_notification_info_maxnum);
        if (number > tooBig) {
            contentView.setTextViewText(R.id.info,
                    context.getResources().getString(R.string.status_bar_notification_info_overflow));
        } else {
            NumberFormat f = NumberFormat.getIntegerInstance();
            contentView.setTextViewText(R.id.info, f.format(number));
        }
        contentView.setViewVisibility(R.id.info, View.VISIBLE);
        showLine3 = true;
    } else {
        contentView.setViewVisibility(R.id.info, View.GONE);
    }

    // Need to show three lines? Only allow on Jellybean+
    if (subText != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        contentView.setTextViewText(R.id.text, subText);
        if (contentText != null) {
            contentView.setTextViewText(R.id.text2, contentText);
            contentView.setViewVisibility(R.id.text2, View.VISIBLE);
            showLine2 = true;
        } else {
            contentView.setViewVisibility(R.id.text2, View.GONE);
        }
    }

    // RemoteViews.setViewPadding and RemoteViews.setTextViewTextSize is not available on ICS-
    if (showLine2 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        if (fitIn1U) {
            // need to shrink all the type to make sure everything fits
            final Resources res = context.getResources();
            final float subTextSize = res.getDimensionPixelSize(R.dimen.notification_subtext_size);
            contentView.setTextViewTextSize(R.id.text, TypedValue.COMPLEX_UNIT_PX, subTextSize);
        }
        // vertical centering
        contentView.setViewPadding(R.id.line1, 0, 0, 0, 0);
    }

    if (when != 0) {
        if (useChronometer) {
            contentView.setViewVisibility(R.id.chronometer, View.VISIBLE);
            contentView.setLong(R.id.chronometer, "setBase",
                    when + (SystemClock.elapsedRealtime() - System.currentTimeMillis()));
            contentView.setBoolean(R.id.chronometer, "setStarted", true);
        } else {
            contentView.setViewVisibility(R.id.time, View.VISIBLE);
            contentView.setLong(R.id.time, "setTime", when);
        }
    }
    contentView.setViewVisibility(R.id.line3, showLine3 ? View.VISIBLE : View.GONE);
    return contentView;
}

From source file:com.sublimis.urgentcallfilter.Magic.java

/**
 * Deletes old numbers from the set ie. numbers with timestamps
 * that have no chance of being eligible for the ring.
 */// w w w.ja va 2s  .  com
private void purgeData() {
    long currentTime = SystemClock.elapsedRealtime();

    if (mData != null && mData.length() > 0) {
        for (int i = 0; i < mData.length(); i++) {
            JSONObject flame = jsonGetObject(mData, i);

            if (flame != null) {
                long timestamp = jsonGetLong(flame, jsonTimestampKey, 0);

                if (timestamp + Config.maxTimePeriod < currentTime) {
                    mData = jsonArrayRemove(mData, i);

                    i--;

                    continue;
                }
            }
        }
    }
}

From source file:com.rc.droid_stalker.components.NetworkStats.java

/**
 * Return age of this {@link NetworkStats} object with respect to
 * {@link SystemClock#elapsedRealtime()}.
 *//*  w w w.  j a v  a  2  s.com*/
public long getElapsedRealtimeAge() {
    return SystemClock.elapsedRealtime() - elapsedRealtime;
}