Example usage for android.os SystemClock uptimeMillis

List of usage examples for android.os SystemClock uptimeMillis

Introduction

In this page you can find the example usage for android.os SystemClock uptimeMillis.

Prototype

@CriticalNative
native public static long uptimeMillis();

Source Link

Document

Returns milliseconds since boot, not counting time spent in deep sleep.

Usage

From source file:org.chromium.chrome.browser.tabmodel.TabPersistentStore.java

public void saveState() {
    // Temporarily allowing disk access. TODO: Fix. See http://b/5518024
    StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
    try {/*  ww  w .  ja va  2 s .  co  m*/
        long saveStateStartTime = SystemClock.uptimeMillis();
        // The list of tabs should be saved first in case our activity is terminated early.
        // Explicitly toss out any existing SaveListTask because they only save the TabModel as
        // it looked when the SaveListTask was first created.
        if (mSaveListTask != null)
            mSaveListTask.cancel(true);
        try {
            saveListToFile(serializeTabMetadata());
        } catch (IOException e) {
            Log.w(TAG, "Error while saving tabs state; will attempt to continue...", e);
        }
        logExecutionTime("SaveListTime", saveStateStartTime);

        // Add current tabs to save because they did not get a save signal yet.
        Tab currentStandardTab = TabModelUtils.getCurrentTab(mTabModelSelector.getModel(false));
        if (currentStandardTab != null && !mTabsToSave.contains(currentStandardTab)
                && currentStandardTab.isTabStateDirty()
                // For content URI, the read permission granted to an activity is not
                // persistent.
                && !isTabUrlContentScheme(currentStandardTab)) {
            mTabsToSave.addLast(currentStandardTab);
        }
        Tab currentIncognitoTab = TabModelUtils.getCurrentTab(mTabModelSelector.getModel(true));
        if (currentIncognitoTab != null && !mTabsToSave.contains(currentIncognitoTab)
                && currentIncognitoTab.isTabStateDirty() && !isTabUrlContentScheme(currentIncognitoTab)) {
            mTabsToSave.addLast(currentIncognitoTab);
        }
        // Wait for the current tab to save.
        if (mSaveTabTask != null) {
            // Cancel calls get() to wait for this to finish internally if it has to.
            // The issue is it may assume it cancelled the task, but the task still actually
            // wrote the state to disk.  That's why we have to check mStateSaved here.
            if (mSaveTabTask.cancel(false) && !mSaveTabTask.mStateSaved) {
                // The task was successfully cancelled.  We should try to save this state again.
                Tab cancelledTab = mSaveTabTask.mTab;
                if (!mTabsToSave.contains(cancelledTab) && cancelledTab.isTabStateDirty()
                        && !isTabUrlContentScheme(cancelledTab)) {
                    mTabsToSave.addLast(cancelledTab);
                }
            }

            mSaveTabTask = null;
        }

        long saveTabsStartTime = SystemClock.uptimeMillis();
        // Synchronously save any remaining unsaved tabs (hopefully very few).
        for (Tab tab : mTabsToSave) {
            int id = tab.getId();
            boolean incognito = tab.isIncognito();
            try {
                TabState state = tab.getState();
                if (state != null) {
                    TabState.saveState(getTabStateFile(id, incognito), state, incognito);
                }
            } catch (OutOfMemoryError e) {
                Log.w(TAG, "Out of memory error while attempting to save tab state.  Erasing.");
                deleteTabState(id, incognito);
            }
        }
        mTabsToSave.clear();
        logExecutionTime("SaveTabsTime", saveTabsStartTime);
        logExecutionTime("SaveStateTime", saveStateStartTime);
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }
}

From source file:com.winneredge.stockly.wcommons.floatingactionwidget.FloatingActionButton.java

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    if (mProgressBarEnabled) {
        if (mShowProgressBackground) {
            canvas.drawArc(mProgressCircleBounds, 360, 360, false, mBackgroundPaint);
        }//www. j  a  va2  s.  c  o m

        boolean shouldInvalidate = false;

        if (mProgressIndeterminate) {
            shouldInvalidate = true;

            long deltaTime = SystemClock.uptimeMillis() - mLastTimeAnimated;
            float deltaNormalized = deltaTime * mSpinSpeed / 1000.0f;

            updateProgressLength(deltaTime);

            mCurrentProgress += deltaNormalized;
            if (mCurrentProgress > 360f) {
                mCurrentProgress -= 360f;
            }

            mLastTimeAnimated = SystemClock.uptimeMillis();
            float from = mCurrentProgress - 90;
            float to = mBarLength + mBarExtraLength;

            if (isInEditMode()) {
                from = 0;
                to = 135;
            }

            canvas.drawArc(mProgressCircleBounds, from, to, false, mProgressPaint);
        } else {
            if (mCurrentProgress != mTargetProgress) {
                shouldInvalidate = true;
                float deltaTime = (float) (SystemClock.uptimeMillis() - mLastTimeAnimated) / 1000;
                float deltaNormalized = deltaTime * mSpinSpeed;

                if (mCurrentProgress > mTargetProgress) {
                    mCurrentProgress = Math.max(mCurrentProgress - deltaNormalized, mTargetProgress);
                } else {
                    mCurrentProgress = Math.min(mCurrentProgress + deltaNormalized, mTargetProgress);
                }
                mLastTimeAnimated = SystemClock.uptimeMillis();
            }

            canvas.drawArc(mProgressCircleBounds, -90, mCurrentProgress, false, mProgressPaint);
        }

        if (shouldInvalidate) {
            invalidate();
        }
    }
}

From source file:cn.isif.util_plus.http.HttpHandler.java

@Override
public boolean updateProgress(long total, long current, boolean forceUpdateUI) {
    if (callback != null && this.state != State.CANCELLED) {
        if (forceUpdateUI) {
            this.publishProgress(UPDATE_LOADING, total, current);
        } else {/*w ww .ja v a  2 s . co  m*/
            long currTime = SystemClock.uptimeMillis();
            if (currTime - lastUpdateTime >= callback.getRate()) {
                lastUpdateTime = currTime;
                this.publishProgress(UPDATE_LOADING, total, current);
            }
        }
    }
    return this.state != State.CANCELLED;
}

From source file:com.example.hellogooglemaps.MarkerDemoActivity.java

@Override
public boolean onMarkerClick(final Marker marker) {
    if (marker.equals(mPerth)) {
        // This causes the marker at Perth to bounce into position when it is clicked.
        final Handler handler = new Handler();
        final long start = SystemClock.uptimeMillis();
        final long duration = 1500;

        final Interpolator interpolator = new BounceInterpolator();

        handler.post(new Runnable() {
            @Override/*from w  ww  .  j  a v  a  2s  . co  m*/
            public void run() {
                long elapsed = SystemClock.uptimeMillis() - start;
                float t = Math.max(1 - interpolator.getInterpolation((float) elapsed / duration), 0);
                marker.setAnchor(0.5f, 1.0f + 2 * t);

                if (t > 0.0) {
                    // Post again 16ms later.
                    handler.postDelayed(this, 16);
                }
            }
        });
    } else if (marker.equals(mAdelaide)) {
        // This causes the marker at Adelaide to change color.
        marker.setIcon(BitmapDescriptorFactory.defaultMarker(new Random().nextFloat() * 360));
    }
    // We return false to indicate that we have not consumed the event and that we wish
    // for the default behavior to occur (which is for the camera to move such that the
    // marker is centered and for the marker's info window to open, if it has one).
    return false;
}

From source file:android.net.http.Connection.java

/**
 * @return true on success/*  www . ja  v a 2s . c o m*/
 */
private boolean openHttpConnection(Request req) {

    long now = SystemClock.uptimeMillis();
    int error = EventHandler.OK;
    Exception exception = null;

    try {
        // reset the certificate to null before opening a connection
        mCertificate = null;
        mHttpClientConnection = openConnection(req);
        if (mHttpClientConnection != null) {
            mHttpClientConnection.setSocketTimeout(SOCKET_TIMEOUT);
            mHttpContext.setAttribute(HTTP_CONNECTION, mHttpClientConnection);
        } else {
            // we tried to do SSL tunneling, failed,
            // and need to drop the request;
            // we have already informed the handler
            req.mFailCount = RETRY_REQUEST_LIMIT;
            return false;
        }
    } catch (UnknownHostException e) {
        if (HttpLog.LOGV)
            HttpLog.v("Failed to open connection");
        error = EventHandler.ERROR_LOOKUP;
        exception = e;
    } catch (IllegalArgumentException e) {
        if (HttpLog.LOGV)
            HttpLog.v("Illegal argument exception");
        error = EventHandler.ERROR_CONNECT;
        req.mFailCount = RETRY_REQUEST_LIMIT;
        exception = e;
    } catch (SSLConnectionClosedByUserException e) {
        // hack: if we have an SSL connection failure,
        // we don't want to reconnect
        req.mFailCount = RETRY_REQUEST_LIMIT;
        // no error message
        return false;
    } catch (SSLHandshakeException e) {
        // hack: if we have an SSL connection failure,
        // we don't want to reconnect
        req.mFailCount = RETRY_REQUEST_LIMIT;
        if (HttpLog.LOGV)
            HttpLog.v("SSL exception performing handshake");
        error = EventHandler.ERROR_FAILED_SSL_HANDSHAKE;
        exception = e;
    } catch (IOException e) {
        error = EventHandler.ERROR_CONNECT;
        exception = e;
    }

    if (HttpLog.LOGV) {
        long now2 = SystemClock.uptimeMillis();
        HttpLog.v("Connection.openHttpConnection() " + (now2 - now) + " " + mHost);
    }

    if (error == EventHandler.OK) {
        return true;
    } else {
        if (req.mFailCount < RETRY_REQUEST_LIMIT) {
            // requeue
            mRequestFeeder.requeueRequest(req);
            req.mFailCount++;
        } else {
            httpFailure(req, error, exception);
        }
        return error == EventHandler.OK;
    }
}

From source file:com.google.io.accessibility.util.IncrementalAsyncTaskLoader.java

@Override
public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
    super.dump(prefix, fd, writer, args);
    if (mTask != null) {
        writer.print(prefix);/*from  w  w  w . j a  v  a 2s.  c  o m*/
        writer.print("mTask=");
        writer.print(mTask);
        writer.print(" waiting=");
        writer.println(mTask.waiting);
    }
    if (mCancellingTask != null) {
        writer.print(prefix);
        writer.print("mCancellingTask=");
        writer.print(mCancellingTask);
        writer.print(" waiting=");
        writer.println(mCancellingTask.waiting);
    }
    if (mUpdateThrottle != 0) {
        writer.print(prefix);
        writer.print("mUpdateThrottle=");
        TimeUtils.formatDuration(mUpdateThrottle, writer);
        writer.print(" mLastLoadCompleteTime=");
        TimeUtils.formatDuration(mLastLoadCompleteTime, SystemClock.uptimeMillis(), writer);
        writer.println();
    }
}

From source file:com.cyrilmottier.android.polaris2demo.MarkerDemoActivity.java

@Override
public boolean onMarkerClick(final Marker marker) {
    // This causes the marker at Perth to bounce into position when it is clicked.
    if (marker.equals(mPerth)) {
        final Handler handler = new Handler();
        final long start = SystemClock.uptimeMillis();
        Projection proj = mMap.getProjection();
        Point startPoint = proj.toScreenLocation(PERTH);
        startPoint.offset(0, -100);//w  ww .jav  a2s  . co m
        final LatLng startLatLng = proj.fromScreenLocation(startPoint);
        final long duration = 1500;

        final Interpolator interpolator = new BounceInterpolator();

        handler.post(new Runnable() {
            @Override
            public void run() {
                long elapsed = SystemClock.uptimeMillis() - start;
                float t = interpolator.getInterpolation((float) elapsed / duration);
                double lng = t * PERTH.longitude + (1 - t) * startLatLng.longitude;
                double lat = t * PERTH.latitude + (1 - t) * startLatLng.latitude;
                marker.setPosition(new LatLng(lat, lng));

                if (t < 1.0) {
                    // Post again 16ms later.
                    handler.postDelayed(this, 16);
                }
            }
        });
    }
    // We return false to indicate that we have not consumed the event and that we wish
    // for the default behavior to occur (which is for the camera to move such that the
    // marker is centered and for the marker's info window to open, if it has one).
    return false;
}

From source file:com.github.shareme.gwsmaterialuikit.library.material.drawable.LineMorphingDrawable.java

private void update() {
    long curTime = SystemClock.uptimeMillis();
    float value = Math.min(1f, (float) (curTime - mStartTime) / mAnimDuration);

    if (value == 1f) {
        setLineState(mCurState, 1f);//from w  w  w  .  j a  v  a  2  s.  com
        mRunning = false;
    } else
        setLineState(mCurState, mInterpolator.getInterpolation(value));

    if (isRunning())
        scheduleSelf(mUpdater, SystemClock.uptimeMillis() + ViewUtil.FRAME_DURATION);
}

From source file:org.mariotaku.twidere.fragment.BaseUsersListFragment.java

@Override
public void onStart() {
    super.onStart();
    mTickerStopped = false;/*from  w ww . j av  a 2 s.co m*/
    mHandler = new Handler();

    mTicker = new Runnable() {

        @Override
        public void run() {
            if (mTickerStopped)
                return;
            if (mListView != null && !mBusy) {
                mAdapter.notifyDataSetChanged();
            }
            final long now = SystemClock.uptimeMillis();
            final long next = now + TICKER_DURATION - now % TICKER_DURATION;
            mHandler.postAtTime(mTicker, next);
        }
    };
    mTicker.run();

    final IntentFilter filter = new IntentFilter();
    filter.addAction(BROADCAST_MULTI_SELECT_STATE_CHANGED);
    filter.addAction(BROADCAST_MULTI_SELECT_ITEM_CHANGED);
    registerReceiver(mStateReceiver, filter);
}

From source file:com.googlecode.talkingrssreader.talkingrss.ReaderHttp.java

public String getArticlesByTag(String tag, String[] exclude, int howMany, String continuation)
        throws ReaderException {
    // Escaping is unclear. Feed in the form http://blabla.com/bla
    // strangely mustn't be escaped, else they won't be
    // recognized. Spaces in user labels need %20 escaping, unclear
    // about other chars.
    if (tag.startsWith("user/") && tag.contains("/label/")) {
        int index = tag.lastIndexOf("/");
        if (index > 0 && index < tag.length() - 1) {
            String tip = tag.substring(index + 1);
            tip = urlEncode(tip).replace("+", "%20");
            tag = tag.substring(0, index + 1) + tip;
        }//from ww  w.  j a v  a2s  .  c om
    }
    String url = ATOM_URL + tag;
    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("n", String.valueOf(howMany)));
    if (continuation != null)
        params.add(new BasicNameValuePair("c", continuation));
    if (exclude != null) {
        for (String x : exclude) {
            params.add(new BasicNameValuePair("xt", x));
        }
    }
    long startTime = SystemClock.uptimeMillis();
    InputStream is = doGet(url, params);
    long readTime = SystemClock.uptimeMillis();
    String out = readAll(is);
    long now = SystemClock.uptimeMillis();
    if (Config.LOGD)
        Log.d(TAG, String.format("Article fetch: request took %dms, transferred %dbytes in %dms",
                readTime - startTime, out.length(), now - readTime));
    return out;
}