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.yeldi.yeldibazaar.UpdateService.java

public static void schedule(Context ctx) {

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
    String sint = prefs.getString("updateInterval", "0");
    int interval = Integer.parseInt(sint);

    Intent intent = new Intent(ctx, UpdateService.class);
    PendingIntent pending = PendingIntent.getService(ctx, 0, intent, 0);

    AlarmManager alarm = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
    alarm.cancel(pending);/*from  w w w  .j  a va 2s.c o m*/
    if (interval > 0) {
        alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 5000,
                AlarmManager.INTERVAL_HOUR, pending);
        Log.d("FDroid", "Update scheduler alarm set");
    } else {
        Log.d("FDroid", "Update scheduler alarm not set");
    }

}

From source file:com.ashish.msngr.GCMNotificationIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();/*ww  w .  j  a v  a  2  s  .c  o m*/
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) {
        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());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {

            for (int i = 0; i < 3; i++) {
                Log.i(TAG, "Working... " + (i + 1) + "/5 @ " + SystemClock.elapsedRealtime());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                }

            }
            Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());

            sendNotification("" + extras.get(Config.MESSAGE_KEY));
            RegisterActivity.msg = (String) extras.get(Config.MESSAGE_KEY);
            Log.i(TAG, "Received: " + extras.toString());
        }
    }
    GcmBroadcastReceiver.completeWakefulIntent(intent);
    //Intent i = new Intent(this,RegisterActivity.class);
    //i.putExtra("msg",msg);
    //startActivity(i);
}

From source file:com.gcm.test.GCMIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    // TODO Auto-generated method stub

    Log.i("GCMIntentService", "sending push notification is" + intent.getStringExtra("message"));
    Bundle extras = intent.getExtras();//w w  w  . j  a va  2s .  c  o  m
    String msg = intent.getStringExtra("message");
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) {

        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(500);
                } catch (InterruptedException e) {
                }
            }
            Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
            // Post notification of received message.
            //sendNotification("Received: " + extras.toString());
            sendNotification(msg);
            Log.i(TAG, "Received: " + extras.toString());
        }
    }
    GCMBroadcastReceiver.completeWakefulIntent(intent);
}

From source file:co.mindquake.nester.pushNoti.GcmIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();//from w w  w .j  a  v a 2  s  .com
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) {

        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
            sendNotification("Send error: " + extras.toString(), extras);
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
            sendNotification("Deleted messages on server: " + extras.toString(), extras);

        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {

            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());

            sendNotification(extras.getString("description"), extras);
            Log.i(TAG, "Received: " + extras.toString());
        }
    }

    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

From source file:com.lovebridge.library.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 {//  w w w .jav  a2 s . c om
            // 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:com.cloudmine.api.rest.CMNetwork.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 = new HashMap<String, String>();
        try {/*from  ww w  .ja  va 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) {
                return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, request.getCacheEntry().data,
                        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 (statusCode > 499) {
                if (responseContents != null) {
                    networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false);
                    attemptRetryOnException("500", request, new ServerError(networkResponse));
                } else {
                    attemptRetryOnException("500", request, new ServerError());
                }
            } else {
                throw new ServerError(networkResponse);
            }
        }
    }
}

From source file:es.javocsoft.android.lib.toolbox.gcm.core.CustomGCMBroadcastReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    Log.d(NotificationModule.TAG, "CustomGCMBroadcastReceiver called.");

    // Explicitly specify that GCMIntentService will handle the intent.
    ComponentName comp = new ComponentName(context.getPackageName(), GCMIntentService.class.getName());

    // Start the service, keeping the device awake while it is launching.
    startWakefulService(context, (intent.setComponent(comp)));
    setResultCode(Activity.RESULT_OK);//from w  ww. jav a  2  s  .  c  o m
    Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
}

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

@Override
public KCHttpResponse performRequest(KCHttpRequest<?> request, KCDeliveryResponse aDelivery) throws KCNetError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
        KCHttpResponse httpResponse = null;
        byte[] responseContents = null;
        KCHeaderGroup responseHeaders = KCHeaderGroup.emptyHeaderGroup();
        try {/*from  ww w . j a v  a  2 s.  c om*/
            // Gather headers.
            KCHeaderGroup additionalHeaders = new KCHeaderGroup();
            addCacheHeaders(additionalHeaders, request.getCacheEntry());
            httpResponse = mHttpStack.performRequest(request, additionalHeaders, aDelivery);
            int statusCode = httpResponse.getStatusCode();

            responseHeaders = httpResponse.getHeaderGroup();
            // Handle cache validation.
            if (statusCode == KCHttpStatus.HTTP_NOT_MODIFIED) {

                KCEntry entry = request.getCacheEntry();
                if (entry == null) {
                    httpResponse.setNotModified(true);
                    httpResponse.setNetworkTimeMs(SystemClock.elapsedRealtime() - requestStart);
                    return httpResponse;
                }

                // 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.addHeaders(responseHeaders.getAllHeaders());

                httpResponse.setNotModified(true);
                httpResponse.setNetworkTimeMs(SystemClock.elapsedRealtime() - requestStart);
                KCHttpContent httpEntity = httpResponse.getHttpContent();
                httpEntity.setContent(entry.data);
                httpResponse.setHeaders(entry.responseHeaders.getAllHeaders());
                return httpResponse;
            }

            responseContents = httpResponse.getContent();

            // Some responses such as 204s do not have content. We must check.
            if (responseContents == null) {
                // 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, statusCode);

            if (statusCode < 200 || statusCode > 299) {
                throw new IOException();
            }

            httpResponse.setNotModified(false);
            httpResponse.setNetworkTimeMs(SystemClock.elapsedRealtime() - requestStart);
            KCHttpContent httpEntity = httpResponse.getHttpContent();
            httpEntity.setContent(responseContents);
            return httpResponse;
        } catch (SocketTimeoutException e) {
            attemptRetryOnException("socket", request, new KCTimeoutError());
        } catch (ConnectTimeoutException e) {
            attemptRetryOnException("connection", request, new KCTimeoutError());
        } 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 KCNoConnectionError(e);
            }
            KCLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());

            KCHttpResponse networkResponse = null;

            if (responseContents != null) {
                networkResponse = ((httpResponse != null) ? httpResponse
                        : new KCHttpResponse(new KCStatusLine(new KCProtocolVersion("HTTP", 1, 1), statusCode,
                                "Unexpected response")));

                networkResponse.setStatusCode(statusCode);
                KCHttpContent httpEntity = networkResponse.getHttpContent();
                if (httpEntity == null) {
                    httpEntity = new KCHttpContent();
                }
                httpEntity.setContent(responseContents);
                networkResponse.setContent(httpEntity);
                networkResponse.setHeaders(responseHeaders.getAllHeaders());
                networkResponse.setNotModified(false);
                networkResponse.setNetworkTimeMs(SystemClock.elapsedRealtime() - requestStart);

                if (statusCode == KCHttpStatus.HTTP_UNAUTHORIZED || statusCode == KCHttpStatus.HTTP_FORBIDDEN) {
                    attemptRetryOnException("auth", request, new KCAuthFailureError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new KCServerError(networkResponse);
                }
            } else {
                throw new KCNetworkError(networkResponse);
            }
        }
    }
}

From source file:com.ab.network.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 = new HashMap<String, String>();
        try {/*  w w w  .j  av  a 2s .c  om*/
            // 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) {
                return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, request.getCacheEntry().data,
                        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:com.google.android.apps.dashclock.PeriodicExtensionRefreshReceiver.java

/**
 * Sets the refresh schedule if one isn't set already.
 *///from  ww w . j  a  va2 s . c o m
public static void updateExtensionsAndEnsurePeriodicRefresh(final Context context) {
    LOGD(TAG, "updateExtensionsAndEnsurePeriodicRefresh");
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    // Update all extensions now.
    context.startService(getUpdateAllExtensionsIntent(context, DashClockExtension.UPDATE_REASON_MANUAL));

    // Schedule an alarm for every 30 minutes; it will not wake up the device;
    // it will be handled only once the device is awake. The first time that this
    // alarm can go off is in 15 minutes, and the latest time it will go off is
    // 45 minutes from now.
    PendingIntent pi = PendingIntent.getBroadcast(context, 0,
            new Intent(context, PeriodicExtensionRefreshReceiver.class).setAction(ACTION_PERIODIC_ALARM),
            PendingIntent.FLAG_UPDATE_CURRENT);
    am.cancel(pi);
    am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + 15 * MINUTES_MILLIS, AlarmManager.INTERVAL_HALF_HOUR, pi);
}