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.oplay.nohelper.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 www .  j  ava 2s  .  com*/
            // 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) {
                Cache.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.
            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 (NetworkError e) {
            VolleyLog.e("%s", "?response");
            continue;
        } catch (IOException e) {
            int statusCode = 0;
            NetworkResponse networkResponse = null;
            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 AuthFailureError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError(networkResponse);
            }
        }
    }
}

From source file:cm.android.download.providers.downloads.DownloadNotifier.java

/**
 * Notify the current speed of an active download, used for calculating
 * estimated remaining time.//from  w  w  w .j  a v a  2  s  .c  om
 */
public void notifyDownloadSpeed(long id, long bytesPerSecond) {
    synchronized (mDownloadSpeed) {
        if (bytesPerSecond != 0) {
            mDownloadSpeed.put(id, bytesPerSecond);
            mDownloadTouch.put(id, SystemClock.elapsedRealtime());
        } else {
            mDownloadSpeed.remove(id);
            mDownloadTouch.remove(id);
        }
    }
}

From source file:com.example.android.camera2video.CameraActivity.java

public static void startLogging(String pathBase) {
    Log.e(TAG, "Logging " + pathBase);
    mLogTime = SystemClock.elapsedRealtime();
    try {//from w w w.j  av a2  s  .co m
        mFileWriter = new FileWriter(pathBase + ".csv");
        mFileWriter.write("//VERSION_NAME " + BuildConfig.VERSION_NAME + "\n");
        mFileWriter.write("//MODEL " + Build.MODEL + "\n");
        mFileWriter.write("//MANUFACTURER " + Build.MANUFACTURER + "\n");
        mFileWriter.write("//HARDWARE " + Build.HARDWARE + "\n");
        mFileWriter.write("//SERIAL " + Build.SERIAL + "\n");
        mFileWriter.write("//ANDROID " + Build.VERSION.RELEASE + "\n");
        mFileWriter.write("//SDK_INT " + Build.VERSION.SDK_INT + "\n");
        mFileWriter.write("//INCREMENTAL " + Build.VERSION.INCREMENTAL + "\n");
        mFileWriter.write("//CODENAME " + Build.VERSION.CODENAME + "\n");
    } catch (IOException e) {
        e.printStackTrace();
    }
    mLogging = true;
}

From source file:com.finchuk.clock2.chronometer.ChronometerNotificationThread.java

/**
 * @param updateText whether the new notification should update its chronometer.
 *                   Use {@code false} if you are updating everything else about the notification,
 *                   e.g. you just want to refresh the actions due to a start/pause state change.
 *///  w  w w  .j  a v  a  2  s  . com
public void updateNotification(boolean updateText) {
    if (updateText) {
        CharSequence text = mDelegate.formatElapsedTime(SystemClock.elapsedRealtime(), mResources);
        mNoteBuilder.setContentText(text);
    }
    mNotificationManager.notify(mNoteTag, mNoteId, mNoteBuilder.build());
}

From source file:com.google.android.apps.muzei.gallery.GalleryEmptyStateGraphicView.java

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if (!isShown() || mWidth == 0 || mHeight == 0) {
        return;/*from w  w  w . j ava  2  s .  c  o  m*/
    }

    // tick timer
    long nowElapsed = SystemClock.elapsedRealtime();
    if (nowElapsed > mOnTime + ON_TIME_MILLIS + FADE_TIME_MILLIS * 2 + OFF_TIME_MILLIS) {
        mOnTime = nowElapsed;
        while (true) {
            int x = mRandom.nextInt(COLS);
            int y = mRandom.nextInt(ROWS);
            if ((x != mOnX || y != mOnY) && BITMAP[y * COLS + x] == 1) {
                mOnX = x;
                mOnY = y;
                break;
            }
        }
    }

    int t = (int) (nowElapsed - mOnTime);
    for (int y = 0; y < ROWS; y++) {
        for (int x = 0; x < COLS; x++) {
            if (BITMAP[y * COLS + x] != 1) {
                continue;
            }

            mTempRectF.set(x * (mCellSize + mCellSpacing), y * (mCellSize + mCellSpacing),
                    x * (mCellSize + mCellSpacing) + mCellSize, y * (mCellSize + mCellSpacing) + mCellSize);

            canvas.drawRoundRect(mTempRectF, mCellRounding, mCellRounding, mOffPaint);

            if (nowElapsed <= mOnTime + ON_TIME_MILLIS + FADE_TIME_MILLIS * 2 && mOnX == x && mOnY == y) {
                // draw items
                if (t < FADE_TIME_MILLIS) {
                    mOnPaint.setAlpha(t * 255 / FADE_TIME_MILLIS);
                } else if (t < FADE_TIME_MILLIS + ON_TIME_MILLIS) {
                    mOnPaint.setAlpha(255);
                } else {
                    mOnPaint.setAlpha((255 - (t - ON_TIME_MILLIS - FADE_TIME_MILLIS) * 255 / FADE_TIME_MILLIS));
                }

                canvas.drawRoundRect(mTempRectF, mCellRounding, mCellRounding, mOnPaint);
            }
        }
    }

    postInvalidateOnAnimation();
}

From source file:com.piggate.samples.PiggateLoginService.Service_Notify.java

@Override
public void onTaskRemoved(Intent rootIntent) {
    Intent restartService = new Intent(getApplicationContext(), this.getClass());
    restartService.setPackage(getPackageName());
    PendingIntent restartServicePI = PendingIntent.getService(getApplicationContext(), 1, restartService,
            PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePI);
}

From source file:com.vis.GcmIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();//from w ww.j av  a 2  s  .  c om
    try {
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        utility = new Utility(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(5000);
                } catch (InterruptedException e) {
                }
                }*/
                Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
                // Post notification of received message.
                String notification = extras.getString("message");
                if (utility.checkInternetConnectivity()) {
                    new WebServiceUtility(getApplicationContext(), Constants.RECIEVE_INFO_TASK, notification);
                }

                sendNotification(notification);
                Log.i(TAG, "Received: " + extras.toString());
            }
        }
    } catch (JsonSyntaxException e) {
        e.printStackTrace();
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

From source file:com.sean.takeastand.alarmprocess.ScheduledRepeatingAlarm.java

@Override
public void delayAlarm() {
    long delayTime = Utils.getNotificationReminderFrequency(mContext);
    long delayTimeInMillis = delayTime * Constants.secondsInMinute * Constants.millisecondsInSecond;
    long triggerTime = SystemClock.elapsedRealtime() + delayTimeInMillis;
    Calendar nextAlarmTime = Calendar.getInstance();
    nextAlarmTime.add(Calendar.MILLISECOND, (int) delayTimeInMillis);
    Utils.setNextAlarmTimeString(nextAlarmTime, mContext);
    setAlarm(triggerTime);/*ww  w  .j  a v  a2s .  c om*/
}

From source file:com.android.cts.uiautomator.Test3DetailFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedState) {
    View rootView = inflater.inflate(R.layout.test3_detail_fragment, container, false);
    mTextClock = (TextView) rootView.findViewById(R.id.test3ClockTextView);
    mSubmitButton = (Button) rootView.findViewById(R.id.test3SubmitButton);
    mEditText = (EditText) rootView.findViewById(R.id.test3TextField);
    mSubmitButton.setOnClickListener(new Button.OnClickListener() {
        @Override//from w w  w .  j a v a 2  s  .  c o m
        public void onClick(View v) {
            // close soft keyboard
            InputMethodManager imm = (InputMethodManager) getActivity()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);

            // display the submitted text
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle(R.string.test3_dialog_title);
            builder.setPositiveButton(R.string.OK, null);
            CharSequence inputText = mEditText.getText();
            if (inputText != null && !inputText.toString().isEmpty()) {
                long inputTime = Long.parseLong(inputText.toString());
                builder.setMessage("" + (mCurrentTime - inputTime));
            } else {
                builder.setMessage("<NO DATA>");
            }
            AlertDialog diag = builder.create();
            diag.show();
            mEditText.setText("");
            mRunCounter = false;
        }
    });

    new Thread(new Runnable() {
        @Override
        public void run() {
            while (mRunCounter) {
                synchronized (sync) {
                    mCurrentTime = SystemClock.elapsedRealtime();
                }
                mHandler.post(mClockRunnable);
                SystemClock.sleep(100);
            }
        }
    }).start();

    return rootView;
}

From source file:com.liato.bankdroid.appwidget.AutoRefreshService.java

public static void showNotification(final Bank bank, final Account account, final BigDecimal diff,
        Context context) {//from  w ww.  j a va  2 s  . c  o  m

    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    if (!prefs.getBoolean("notify_on_change", true)) {
        return;
    }

    String text = String.format("%s: %s%s", account.getName(),
            ((diff.compareTo(new BigDecimal(0)) == 1) ? "+" : ""),
            Helpers.formatBalance(diff, account.getCurrency()));
    if (!prefs.getBoolean("notify_delta_only", false)) {
        text = String.format("%s (%s)", text,
                Helpers.formatBalance(account.getBalance(), account.getCurrency()));
    }

    final NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(NOTIFICATION_SERVICE);
    final NotificationCompat.Builder notification = new NotificationCompat.Builder(context)
            .setSmallIcon(bank.getImageResource()).setContentTitle(bank.getDisplayName()).setContentText(text);

    // Remove notification from statusbar when clicked
    notification.setAutoCancel(true);

    // http://www.freesound.org/samplesViewSingle.php?id=75235
    // http://www.freesound.org/samplesViewSingle.php?id=91924
    if (prefs.getString("notification_sound", null) != null) {
        notification.setSound(Uri.parse(prefs.getString("notification_sound", null)));
    }
    if (prefs.getBoolean("notify_with_vibration", true)) {
        final long[] vib = { 0, 90, 130, 80, 350, 190, 20, 380 };
        notification.setVibrate(vib);
    }

    if (prefs.getBoolean("notify_with_led", true)) {
        notification.setLights(prefs.getInt("notify_with_led_color",
                context.getResources().getColor(R.color.default_led_color)), 700, 200);
    }

    final PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
            new Intent(context, MainActivity.class), 0);
    notification.setContentIntent(contentIntent);

    String numNotifications = prefs.getString("num_notifications", "total");
    int notificationId = (int) (numNotifications.equals("total") ? 0
            : numNotifications.equals("bank") ? bank.getDbId()
                    : numNotifications.equals("account") ? account.getId().hashCode()
                            : SystemClock.elapsedRealtime());
    notificationManager.notify(notificationId, notification.build());

    // Broadcast to Remote Notifier if enabled
    // http://code.google.com/p/android-notifier/
    if (prefs.getBoolean("notify_remotenotifier", false)) {
        final Intent i = new Intent(BROADCAST_REMOTE_NOTIFIER);
        i.putExtra("title", String.format("%s (%s)", bank.getName(), bank.getDisplayName()));
        i.putExtra("description", text);
        context.sendBroadcast(i);
    }

    // Broadcast to OpenWatch if enabled
    // http://forum.xda-developers.com/showthread.php?t=554551
    if (prefs.getBoolean("notify_openwatch", false)) {
        Intent i;
        if (prefs.getBoolean("notify_openwatch_vibrate", false)) {
            i = new Intent(BROADCAST_OPENWATCH_VIBRATE);
        } else {
            i = new Intent(BROADCAST_OPENWATCH_TEXT);
        }
        i.putExtra("line1", String.format("%s (%s)", bank.getName(), bank.getDisplayName()));
        i.putExtra("line2", text);
        context.sendBroadcast(i);
    }

    // Broadcast to LiveView if enabled
    // http://www.sonyericsson.com/cws/products/accessories/overview/liveviewmicrodisplay
    if (prefs.getBoolean("notify_liveview", false)) {
        final Intent i = new Intent(context, LiveViewService.class);
        i.putExtra(LiveViewService.INTENT_EXTRA_ANNOUNCE, true);
        i.putExtra(LiveViewService.INTENT_EXTRA_TITLE,
                String.format("%s (%s)", bank.getName(), bank.getDisplayName()));
        i.putExtra(LiveViewService.INTENT_EXTRA_TEXT, text);
        context.startService(i);
    }

}