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.google.android.gcm.GCMBaseIntentService.java

private void handleRegistration(final Context context, Intent intent) {
    String registrationId = intent.getStringExtra(EXTRA_REGISTRATION_ID);
    String error = intent.getStringExtra(EXTRA_ERROR);
    String unregistered = intent.getStringExtra(EXTRA_UNREGISTERED);
    Log.d(TAG, "handleRegistration: registrationId = " + registrationId + ", error = " + error
            + ", unregistered = " + unregistered);

    // registration succeeded
    if (registrationId != null) {
        GCMRegistrar.resetBackoff(context);
        GCMRegistrar.setRegistrationId(context, registrationId);
        onRegistered(context, registrationId);
        return;/* w  w w  .jav a 2 s .co  m*/
    }

    // unregistration succeeded
    if (unregistered != null) {
        // Remember we are unregistered
        GCMRegistrar.resetBackoff(context);
        String oldRegistrationId = GCMRegistrar.clearRegistrationId(context);
        onUnregistered(context, oldRegistrationId);
        return;
    }

    // last operation (registration or unregistration) returned an error;
    Log.d(TAG, "Registration error: " + error);
    // Registration failed
    if (ERROR_SERVICE_NOT_AVAILABLE.equals(error)) {
        boolean retry = onRecoverableError(context, error);
        if (retry) {
            int backoffTimeMs = GCMRegistrar.getBackoff(context);
            int nextAttempt = backoffTimeMs / 2 + sRandom.nextInt(backoffTimeMs);
            Log.d(TAG, "Scheduling registration retry, backoff = " + nextAttempt + " (" + backoffTimeMs + ")");
            Intent retryIntent = new Intent(INTENT_FROM_GCM_LIBRARY_RETRY);
            retryIntent.putExtra(EXTRA_TOKEN, TOKEN);
            PendingIntent retryPendingIntent = PendingIntent.getBroadcast(context, 0, retryIntent, 0);
            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            am.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + nextAttempt,
                    retryPendingIntent);
            // Next retry should wait longer.
            if (backoffTimeMs < MAX_BACKOFF_MS) {
                GCMRegistrar.setBackoff(context, backoffTimeMs * 2);
            }
        } else {
            Log.d(TAG, "Not retrying failed operation");
        }
    } else {
        // Unrecoverable error, notify app
        onError(context, error);
    }
}

From source file:at.alladin.rmbt.android.test.RMBTLoopService.java

private void setAlarm(long millis) {
    Log.d(TAG, "setAlarm: " + millis);

    final long now = SystemClock.elapsedRealtime();
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, now + millis, alarm);
}

From source file:br.com.bioscada.apps.biotracks.widgets.TrackWidgetProvider.java

/**
 * Sets a widget item.// w w  w  .ja v  a  2s .c om
 * 
 * @param context the context
 * @param remoteViews the remote view
 * @param ids the item's ids
 * @param value the item value
 * @param tripStatistics the trip statistics
 * @param metricUnits true to use metric units
 * @param reportSpeed try to report speed
 */
private static void setItem(Context context, RemoteViews remoteViews, int[] ids, int value,
        TripStatistics tripStatistics, boolean isRecording, boolean isPaused, boolean metricUnits,
        boolean reportSpeed) {
    switch (value) {
    case 0:
        updateDistance(context, remoteViews, ids, tripStatistics, metricUnits);
        break;
    case 1:
        updateTotalTime(context, remoteViews, ids, tripStatistics, isRecording, isPaused);
        break;
    case 2:
        updateAverageSpeed(context, remoteViews, ids, tripStatistics, metricUnits, reportSpeed);
        break;
    case 3:
        updateMovingTime(context, remoteViews, ids, tripStatistics);
        break;
    case 4:
        updateAverageMovingSpeed(context, remoteViews, ids, tripStatistics, metricUnits, reportSpeed);
        break;
    default:
        updateDistance(context, remoteViews, ids, tripStatistics, metricUnits);
        break;

    }
    if (value != 1) {
        remoteViews.setViewVisibility(ids[1], View.VISIBLE);
        remoteViews.setViewVisibility(ids[2], View.VISIBLE);
        remoteViews.setViewVisibility(ids[3], View.GONE);
        remoteViews.setChronometer(ids[3], SystemClock.elapsedRealtime(), null, false);
    }
}

From source file:com.swetha.easypark.GetIndividualParkingSpotDetails.java

private void scheduleNotification(Notification notification) {

    Intent notificationIntent = new Intent(this, NotificationPublisher.class);
    notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, Integer.parseInt(theParkingSpotId));
    notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    long currentTimeInLong = DateTimeHelpers
            .convertToLongFromTime(DateTimeHelpers.dtf.format(new Date()).toString());
    long delay = toTime - (currentTimeInLong + Constants.tenMinutesInMilliseconds);
    long futureInMills = SystemClock.elapsedRealtime() + delay;

    Log.i("GetIndividualParkingSpotDetails", " Spot has been blocked till long " + toTime);
    Log.i("GetIndividualParkingSpotDetails",
            " Spot has been blocked till  DateTime" + DateTimeHelpers.convertToTimeFromLong(toTime));

    Log.i("GetIndividualParkingSpotDetails", " CurrentTime in  long " + currentTimeInLong);
    Log.i("GetIndividualParkingSpotDetails",
            " Spot has been blocked till  DateTime" + DateTimeHelpers.convertToTimeFromLong(currentTimeInLong));

    Log.i("GetIndividualParkingSpotDetails", "value of delay" + delay);
    Log.i("GetIndividualParkingSpotDetails",
            "value of mills in time" + DateTimeHelpers.convertToTimeFromLong(futureInMills));

    Log.i("GetIndividualParkingSpotDetails", "Notification is kept at this mills" + futureInMills);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMills, pendingIntent);

}

From source file:com.achow101.bitcointalkforum.MainActivity.java

public void onResume() {
    super.onResume();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    int seconds = Integer.parseInt(prefs.getString("notifications_sync_freq", "60"));
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    Intent i = new Intent(this, NotificationService.class);
    i.putExtra("SESSION ID", sessId);
    i.putExtra("Username", mUsername);
    PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
    am.cancel(pi);/*from ww  w.  ja  v a  2 s. co  m*/

    if (prefs.getBoolean("notifications_new_message", true)) {
        am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + seconds * 1000, seconds * 1000, pi);
    }
}

From source file:com.anysoftkeyboard.keyboards.views.AnyKeyboardBaseView.java

public boolean isAtTwoFingersState() {
    //this is a hack, I know.
    //I know that this is a swipe ONLY after the second finger is up, so I already lost the
    //two-fingers count in the motion event.
    return SystemClock.elapsedRealtime() - mLastTimeHadTwoFingers < TWO_FINGERS_LINGER_TIME;
}

From source file:com.baseproject.volley.toolbox.LruDiskBasedCache.java

/**
 * Prunes the cache to fit the amount of bytes specified.
 * //from   ww  w . j ava 2  s.  co m
 * @param neededSpace
 *            The amount of bytes we are trying to fit into the cache.
 */
private void pruneIfNeeded(int neededSpace) {
    if ((mTotalSize + neededSpace) < mMaxCacheSizeInBytes) {
        return;
    }
    if (VolleyLog.DEBUG) {
        VolleyLog.v("Pruning old cache entries.");
    }

    long before = mTotalSize;
    int prunedFiles = 0;
    long startTime = SystemClock.elapsedRealtime();

    Iterator<Map.Entry<String, CacheHeader>> iterator = mEntries.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry<String, CacheHeader> entry = iterator.next();
        CacheHeader e = entry.getValue();
        boolean deleted = getFileForKey(e.key).delete();
        if (deleted) {
            mTotalSize -= e.size;
        } else {
            VolleyLog.d("Could not delete cache entry for key=%s, filename=%s", e.key,
                    getFilenameForKey(e.key));
        }
        iterator.remove();
        prunedFiles++;

        if ((mTotalSize + neededSpace) < mMaxCacheSizeInBytes * HYSTERESIS_FACTOR) {
            break;
        }
    }
    if (VolleyLog.DEBUG) {
        VolleyLog.v("pruned %d files, %d bytes, %d ms", prunedFiles, (mTotalSize - before),
                SystemClock.elapsedRealtime() - startTime);
    }
}

From source file:com.google.android.gcm.demo.ui.NetworkSchedulerFragment.java

@Override
public void refresh() {
    FrameLayout tasksView = (FrameLayout) getActivity().findViewById(R.id.scheduler_tasks);
    // the view might have been destroyed, in which case we don't do anything
    if (tasksView != null) {
        float density = getActivity().getResources().getDisplayMetrics().density;
        SimpleArrayMap<String, TaskTracker> tasks = mTasks.getTasks();
        LinearLayout tasksList = new LinearLayout(getActivity());
        tasksList.setOrientation(LinearLayout.VERTICAL);
        for (int i = 0; i < tasks.size(); i++) {
            final TaskTracker task = tasks.valueAt(i);
            CardView taskCard = (CardView) getActivity().getLayoutInflater().inflate(R.layout.widget_task,
                    tasksList, false);/*from   ww  w  . j a va2  s .  c om*/
            ImageView taskIcon = (ImageView) taskCard.findViewById(R.id.task_icon);
            taskIcon.setImageResource(R.drawable.check_circle_grey600);
            taskIcon.setPadding(0, 0, (int) (8 * density), 0);
            TextView taskLabel = (TextView) taskCard.findViewById(R.id.task_title);
            TextView taskParams = (TextView) taskCard.findViewById(R.id.task_params);
            if (task.period == 0) {
                taskLabel.setText(getString(R.string.scheduler_oneoff, task.tag));
                taskParams.setText(getString(R.string.scheduler_oneoff_params, task.windowStartElapsedSecs,
                        task.windowStopElapsedSecs));
            } else {
                taskLabel.setText(getString(R.string.scheduler_periodic, task.tag));
                taskParams.setText(getString(R.string.scheduler_periodic_params, task.period, task.flex));
            }
            TextView taskCreatedAt = (TextView) taskCard.findViewById(R.id.task_created_at);
            taskCreatedAt.setText(getString(R.string.scheduler_secs_ago, DateUtils
                    .formatElapsedTime(SystemClock.elapsedRealtime() / 1000 - task.createdAtElapsedSecs)));
            TextView lastExecuted = (TextView) taskCard.findViewById(R.id.task_last_exec);
            if (task.executionTimes.isEmpty()) {
                lastExecuted.setText(getString(R.string.scheduler_na));
            } else {
                long lastExecTime = task.executionTimes.get(task.executionTimes.size() - 1);
                lastExecuted.setText(getString(R.string.scheduler_secs_ago,
                        DateUtils.formatElapsedTime(SystemClock.elapsedRealtime() / 1000 - lastExecTime)));
            }
            TextView state = (TextView) taskCard.findViewById(R.id.task_state);
            if (task.isCancelled()) {
                state.setText(getString(R.string.scheduler_cancelled));
            } else if (task.isExecuted()) {
                state.setText(getString(R.string.scheduler_executed));
            } else {
                state.setText(getString(R.string.scheduler_pending));
            }
            Button cancel = (Button) taskCard.findViewById(R.id.task_cancel);
            cancel.setVisibility(View.VISIBLE);
            cancel.setText(R.string.scheduler_cancel);
            Button delete = (Button) taskCard.findViewById(R.id.task_delete);
            delete.setVisibility(View.VISIBLE);
            delete.setText(R.string.scheduler_delete);
            if (!task.isCancelled() && (!task.isExecuted() || task.period != 0)) {
                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        cancelTask(task.tag);
                        refresh();
                    }
                });
                cancel.setEnabled(true);
                delete.setEnabled(false);
            } else {
                cancel.setEnabled(false);
                delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mTasks.deleteTask(task.tag);
                        refresh();
                    }
                });
                delete.setEnabled(true);
            }
            tasksList.addView(taskCard);
        }
        tasksView.removeAllViews();
        tasksView.addView(tasksList);
    }
}

From source file:com.psiphon3.psiphonlibrary.UpgradeChecker.java

/**
 * Creates the periodic alarm used to check for updates. Can be called unconditionally; it
 * handles cases when the alarm is already created.
 * @param appContext The application context.
 *///w  ww  .j a v  a  2  s . co  m
private static void createAlarm(Context appContext) {
    if (!allowedToSelfUpgrade(appContext)) {
        // Don't waste resources with an alarm if we can't possibly self-upgrade.
        log(appContext, R.string.upgrade_checker_no_alarm_no_selfupgrading, MyLog.Sensitivity.NOT_SENSITIVE,
                Log.WARN);
        return;
    }

    Intent intent = new Intent(appContext, UpgradeChecker.class);
    intent.setAction(ALARM_INTENT_ACTION);

    boolean alarmExists = (PendingIntent.getBroadcast(appContext, ALARM_INTENT_REQUEST_CODE, intent,
            PendingIntent.FLAG_NO_CREATE) != null);

    if (alarmExists) {
        log(appContext, R.string.upgrade_checker_alarm_exists, MyLog.Sensitivity.NOT_SENSITIVE, Log.WARN);
        return;
    }

    log(appContext, R.string.upgrade_checker_creating_alarm, MyLog.Sensitivity.NOT_SENSITIVE, Log.WARN);

    PendingIntent alarmIntent = PendingIntent.getBroadcast(appContext, ALARM_INTENT_REQUEST_CODE, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarmMgr = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
    alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_FIFTEEN_MINUTES,
            AlarmManager.INTERVAL_HALF_DAY, alarmIntent);
}

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

private void insertNewRing() {
    if (mData != null) {
        long currentTime = SystemClock.elapsedRealtime();

        JSONObject obj = new JSONObject();

        jsonPutString(obj, jsonNumberKey, mNumber);
        jsonPutLong(obj, jsonTimestampKey, currentTime);
        jsonPutLong(obj, jsonRingDurationKey, 0);

        mData.put(obj);/*w w  w  .ja v a  2s . co  m*/
    }
}