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.hiyjeain.android.DevBase.volley.toolbox.BasicNetwork.java

@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
        HttpResponse httpResponse = null;
        byte[] responseContents = null;
        Map<String, String> responseHeaders = Collections.emptyMap();
        try {/*from   w ww.  jav a 2 s. c  o m*/
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            addCacheHeaders(headers, request.getCacheEntry());
            httpResponse = mHttpStack.performRequest(request, headers);
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();

            responseHeaders = convertHeaders(httpResponse.getAllHeaders());
            // Handle cache validation.
            if (statusCode == HttpStatus.SC_NOT_MODIFIED) {

                Entry entry = request.getCacheEntry();
                if (entry == null) {
                    return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, null, responseHeaders, true);
                }

                // A HTTP 304 response does not have all header fields. We
                // have to use the header fields from the cache entry plus
                // the new ones from the response.
                // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
                entry.responseHeaders.putAll(responseHeaders);
                return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, entry.data, entry.responseHeaders, true);
            }

            // Some responses such as 204s do not have content.  We must check.
            if (httpResponse.getEntity() != null) {
                responseContents = entityToBytes(httpResponse.getEntity());
            } else {
                // Add 0 byte response as a way of honestly representing a
                // no-content request.
                responseContents = new byte[0];
            }

            // if the request is slow, log it.
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
            logSlowRequests(requestLifetime, request, responseContents, statusLine);

            if (statusCode < 200 || statusCode > 299) {
                throw new IOException();
            }
            return new NetworkResponse(statusCode, responseContents, responseHeaders, false);
        } catch (SocketTimeoutException e) {
            attemptRetryOnException("socket", request, new TimeoutError());
        } catch (ConnectTimeoutException e) {
            attemptRetryOnException("connection", request, new TimeoutError());
        } catch (MalformedURLException e) {
            throw new RuntimeException("Bad URL " + request.getUrl(), e);
        } catch (IOException e) {
            int statusCode = 0;
            NetworkResponse networkResponse = null;
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusLine().getStatusCode();
            } else {
                throw new NoConnectionError(e);
            }
            VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            if (responseContents != null) {
                networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false);
                if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError(networkResponse);
            }
        }
    }
}

From source file:cn.studyjams.s2.sj0119.NForget.AlarmReceiver.java

public void setAlarm(Context context, Calendar calendar, int ID) {
    mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    // Put Reminder ID in Intent Extra
    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.putExtra(ReminderEditActivity.EXTRA_REMINDER_ID, Integer.toString(ID));
    mPendingIntent = PendingIntent.getBroadcast(context, ID, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    // Calculate notification time
    Calendar c = Calendar.getInstance();
    long currentTime = c.getTimeInMillis();
    long diffTime = calendar.getTimeInMillis() - currentTime;

    // Start alarm using notification time
    mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + diffTime, mPendingIntent);

    // Restart alarm if device is rebooted
    ComponentName receiver = new ComponentName(context, BootReceiver.class);
    PackageManager pm = context.getPackageManager();
    pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);
}

From source file:com.phonemetra.account.util.AccountUtils.java

public static void scheduleAccountPing(Context context, Intent intent) {
    if (Account.DEBUG)
        Log.d(TAG,/*from ww  w .  j a  v a 2s .c o m*/
                "Scheduling Account ping, starting = "
                        + new Timestamp(SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY)
                        + " interval (" + AlarmManager.INTERVAL_DAY + ")");
    PendingIntent reRegisterPendingIntent = PendingIntent.getService(context, 0, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,
            SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY, AlarmManager.INTERVAL_DAY,
            reRegisterPendingIntent);
}

From source file:com.qurater.pivotal.gcm.GcmIntentServiceV2.java

@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();/*  ww  w. j  a  va 2  s . c  om*/
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    // The getMessageType() intent parameter must be the intent you received
    // in your BroadcastReceiver.
    String messageType = gcm.getMessageType(intent);

    if (extras != null && !extras.isEmpty()) { // has effect of unparcelling Bundle
        /*
         * Filter messages based on message type. Since it is likely that GCM will be
         * extended in the future with new message types, just ignore any message types you're
         * not interested in, or that you don't recognize.
         */
        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
            //sendNotification("Send error: " + extras.toString());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
            //sendNotification("Deleted messages on server: " + extras.toString());
            // If it's a regular GCM message, do some work.
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
            // This loop represents the service doing some work.
            /*
            for (int i = 0; i < 5; i++) {
            Log.i(TAG, "Working... " + (i + 1)
                    + "/5 @ " + SystemClock.elapsedRealtime());
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
            }
            }*/
            Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
            // Post notification of received message.
            sendNotification(extras);
            Log.i(TAG, "Received: " + extras.toString());
        }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

From source file:ar.com.martinrevert.argenteam.GcmIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    String message;/*from  w w  w  . jav  a 2  s .  c o  m*/
    String tipo;
    String urlimagen;
    String urlarticulo;
    String fecha;

    Context context = getApplicationContext();

    Bundle extras = intent.getExtras();

    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    // The getMessageType() intent parameter must be the intent you received
    // in your BroadcastReceiver.
    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) { // has effect of unparcelling Bundle
        /*
         * Filter messages based on message type. Since it is likely that GCM will be
         * extended in the future with new message types, just ignore any message types you're
         * not interested in, or that you don't recognize.
         */
        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
            generarNotification(context, "Error: " + extras.toString(), "", "", "", "");
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
            generarNotification(context, "Deleted messages on server: " + extras.toString(), "", "", "", "");
            // If it's a regular GCM message, do some work.
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
            // Aqui obtengo los datos del mensaje que viene en el Intent.
            message = intent.getExtras().getString("message");
            tipo = intent.getExtras().getString("tipo");
            urlimagen = intent.getExtras().getString("urlimagen");
            urlarticulo = intent.getExtras().getString("urlarticulo");
            fecha = intent.getExtras().getString("fecha");
            Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
            // Post notification of received message.
            generarNotification(context, message, urlimagen, urlarticulo, tipo, fecha);
            Log.i(TAG, "Received: " + extras.toString());
        }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

From source file:com.selene.volley.tool.BasicNetwork.java

@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    // Determine if request had non-http perform.
    NetworkResponse networkResponse = request.perform();
    if (networkResponse != null) {
        return networkResponse;
    }/*from   ww  w. j a v a  2  s  .c o m*/
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
        // If the request was cancelled already,
        // do not perform the network request.
        if (request.isCanceled()) {
            request.finish("perform-discard-cancelled");
            mDelivery.postCancel(request);
            throw new NetworkError(networkResponse);
        }
        HttpResponse httpResponse = null;
        byte[] responseContents = null;
        Map<String, String> responseHeaders = Collections.emptyMap();
        try {
            // prepare to perform this request, normally is reset the request headers.
            request.prepare();
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            addCacheHeaders(headers, request.getCacheEntry());
            httpResponse = mHttpStack.performRequest(request, headers);
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            responseHeaders = convertHeaders(httpResponse.getAllHeaders());
            responseContents = request.handleResponse(httpResponse, mDelivery);
            // Handle cache validation.
            if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
                Entry entry = request.getCacheEntry();
                if (entry == null) {
                    return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, null, responseHeaders, true,
                            SystemClock.elapsedRealtime() - requestStart);
                }
                // A HTTP 304 response does not have all header fields. We
                // have to use the header fields from the cache entry plus
                // the new ones from the response.
                // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
                entry.responseHeaders.putAll(responseHeaders);
                return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, entry.data, entry.responseHeaders, true,
                        SystemClock.elapsedRealtime() - requestStart);
            }
            // Handle moved resources
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                    || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                String newUrl = responseHeaders.get("Location");
                request.setRedirectUrl(newUrl);
            }

            // Some responses such as 204s do not have content. We must check. alternative by handleResponse
            //            if (httpResponse.getEntity() != null) {
            //               responseContents = entityToBytes(httpResponse.getEntity());
            //            } else {
            //               // Add 0 byte response as a way of honestly representing a
            //               // no-content request.
            //               responseContents = new byte[0];
            //            }

            // if the request is slow, log it.
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
            logSlowRequests(requestLifetime, request, responseContents, statusLine);

            if (statusCode < 200 || statusCode > 299) {
                throw new IOException();
            }
            return new NetworkResponse(statusCode, responseContents, responseHeaders, false,
                    SystemClock.elapsedRealtime() - requestStart);
        } catch (SocketTimeoutException e) {
            attemptRetryOnException("socket", request, new TimeoutError());
        } catch (ConnectTimeoutException e) {
            attemptRetryOnException("connection", request, new TimeoutError());
        } catch (MalformedURLException e) {
            throw new RuntimeException("Bad URL " + request.getUrl(), e);
        } catch (IOException e) {
            int statusCode = 0;
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusLine().getStatusCode();
            } else {
                throw new NoConnectionError(e);
            }
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                    || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                VolleyLog.e("Request at %s has been redirected to %s", request.getOriginUrl(),
                        request.getUrl());
            } else {
                VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            }
            if (responseContents != null) {
                networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false,
                        SystemClock.elapsedRealtime() - requestStart);
                if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                        || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                    attemptRetryOnException("redirect", request, new RedirectError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError(networkResponse);
            }
        }
    }
}

From source file:com.appsaur.tarucassist.AutomuteAlarmReceiver.java

public void setAlarm(Context context, Calendar calendar, int ID) {
    mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    // Put Reminder ID in Intent Extra
    Intent intent = new Intent(context, AutomuteAlarmReceiver.class);
    intent.putExtra(BaseActivity.EXTRA_REMINDER_ID, Integer.toString(ID));
    mPendingIntent = PendingIntent.getBroadcast(context, ID, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    // Calculate notification time
    Calendar c = Calendar.getInstance();
    long currentTime = c.getTimeInMillis();
    long diffTime = calendar.getTimeInMillis() - currentTime;

    // Start alarm using notification time
    mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + diffTime, mPendingIntent);

    // Restart alarm if device is rebooted
    ComponentName receiver = new ComponentName(context, BootReceiver.class);
    PackageManager pm = context.getPackageManager();
    pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);
}

From source file:com.example.volunteerhandbook.GcmIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();//from   w w w.  j av  a  2 s .  co m
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    // The getMessageType() intent parameter must be the intent you received
    // in your BroadcastReceiver.
    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) { // has effect of unparcelling Bundle
        /*
         * Filter messages based on message type. Since it is likely that GCM will be
         * extended in the future with new message types, just ignore any message types you're
         * not interested in, or that you don't recognize.
         */
        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
            sendNotification("Send error: " + extras.toString());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
            sendNotification("Deleted messages on server: " + extras.toString());
            // If it's a regular GCM message, do some work.
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
            // This loop represents the service doing some work.
            for (int i = 0; i < 5; i++) {
                Log.i(TAG, "Working... " + (i + 1) + "/5 @ " + SystemClock.elapsedRealtime());
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                }
            }
            Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
            // Post notification of received message.
            sendNotification("Received: " + extras.toString());
            Log.i(TAG, "Received: " + extras.toString());
        }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

From source file:alaindc.memenguage.RandomIntentService.java

private void setTimeout() {
    // Set the alarms for next sensing of amplitude
    alarmMgr = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);

    Intent intentAlarm = new Intent(getApplicationContext(), RandomIntentService.class);
    intentAlarm.setAction(Constants.ACTION_RANDOM_WORD);
    alarmIntent = PendingIntent.getService(getApplicationContext(), 0, intentAlarm, 0);

    try {/*from  w  w w . j a v  a2s  .c  o  m*/
        // Remove the oldest one if exists
        alarmMgr.cancel(alarmIntent);
    } catch (Exception e) {
        Log.d("Randomintentservice", "Cancel pending intent error");
    }

    long millisec = Long.parseLong(
            PreferenceManager.getDefaultSharedPreferences(this).getString("interval_notifications", "120")) * 60
            * 1000;
    alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + millisec, alarmIntent);
}

From source file:com.androidinspain.deskclock.timer.TimerItem.java

/**
 * Updates this view to display the latest state of the {@code timer}.
 *///from w  w w  . j  a  va2 s  .  co m
void update(Timer timer) {
    // Update the time.
    mTimerTextController.setTimeString(timer.getRemainingTime());

    // Update the label if it changed.
    final String label = timer.getLabel();
    if (!TextUtils.equals(label, mLabelView.getText())) {
        mLabelView.setText(label);
    }

    // Update visibility of things that may blink.
    final boolean blinkOff = SystemClock.elapsedRealtime() % 1000 < 500;
    if (mCircleView != null) {
        final boolean hideCircle = (timer.isExpired() || timer.isMissed()) && blinkOff;
        mCircleView.setVisibility(hideCircle ? INVISIBLE : VISIBLE);

        if (!hideCircle) {
            // Update the progress of the circle.
            mCircleView.update(timer);
        }
    }
    if (!timer.isPaused() || !blinkOff || mTimerText.isPressed()) {
        mTimerText.setAlpha(1f);
    } else {
        mTimerText.setAlpha(0f);
    }

    // Update some potentially expensive areas of the user interface only on state changes.
    if (timer.getState() != mLastState) {
        mLastState = timer.getState();
        final Context context = getContext();
        switch (mLastState) {
        case RESET:
        case PAUSED: {
            mResetAddButton.setText(R.string.timer_reset);
            mResetAddButton.setContentDescription(null);
            mTimerText.setClickable(true);
            mTimerText.setActivated(false);
            mTimerText.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
            ViewCompat.setAccessibilityDelegate(mTimerText,
                    new ClickAccessibilityDelegate(context.getString(R.string.timer_start), true));
            break;
        }
        case RUNNING: {
            final String addTimeDesc = context.getString(R.string.timer_plus_one);
            mResetAddButton.setText(R.string.timer_add_minute);
            mResetAddButton.setContentDescription(addTimeDesc);
            mTimerText.setClickable(true);
            mTimerText.setActivated(false);
            mTimerText.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
            ViewCompat.setAccessibilityDelegate(mTimerText,
                    new ClickAccessibilityDelegate(context.getString(R.string.timer_pause)));
            break;
        }
        case EXPIRED:
        case MISSED: {
            final String addTimeDesc = context.getString(R.string.timer_plus_one);
            mResetAddButton.setText(R.string.timer_add_minute);
            mResetAddButton.setContentDescription(addTimeDesc);
            mTimerText.setClickable(false);
            mTimerText.setActivated(true);
            mTimerText.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
            break;
        }
        }
    }
}