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:com.android.gallery3d.ingest.IngestService.java

@Override
public void onObjectIndexed(IngestObjectInfo object, int numVisited) {
    mNeedRelaunchNotification = false;//from  ww w  .ja  va 2 s. c  o  m
    if (mClientActivity != null) {
        mClientActivity.onObjectIndexed(object, numVisited);
    } else {
        // Throttle the updates to one every PROGRESS_UPDATE_INTERVAL_MS milliseconds
        long currentTime = SystemClock.uptimeMillis();
        if (currentTime > mLastProgressIndexTime + PROGRESS_UPDATE_INTERVAL_MS) {
            mLastProgressIndexTime = currentTime;
            mNotificationBuilder.setProgress(0, numVisited, true)
                    .setContentText(getResources().getText(R.string.ingest_scanning));
            mNotificationManager.notify(R.id.ingest_notification_scanning, mNotificationBuilder.build());
        }
    }
}

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

public String login(String username, String password) throws ReaderException {
    if (Config.LOGD)
        Log.d(TAG, "Logging in");
    long startTime = SystemClock.uptimeMillis();
    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("accountType", "HOSTED_OR_GOOGLE"));
    params.add(new BasicNameValuePair("Email", username));
    params.add(new BasicNameValuePair("Passwd", password));
    params.add(new BasicNameValuePair("service", "reader"));
    params.add(new BasicNameValuePair("source", AGENT_STRING));
    String reply;/* ww  w  . ja v a  2  s .c  o m*/
    try {
        reply = readAll(doPost(GOOGLE_LOGIN_URL, params, false));
    } catch (HttpForbiddenException e) {
        return null;
    }
    long now = SystemClock.uptimeMillis();
    if (Config.LOGD)
        Log.d(TAG, String.format("Login request took %dms", now - startTime));
    int index = reply.indexOf("Auth=");
    if (index > -1) {
        int end = reply.indexOf('\n', index);
        if (end > index + 5) {
            String authToken = reply.substring(index + 5, end);
            return authToken;
        }
    }
    throw new ProtocolException("Failed to parse login reply");
}

From source file:com.example.google.play.apkx.SampleDownloaderActivity.java

/**
 * Go through each of the Expansion APK files and open each as a zip file.
 * Calculate the CRC for each file and return false if any fail to match.
 *
 * @return true if XAPKZipFile is successful
 *//*from   w w  w .  j a va  2  s  .  com*/
void validateXAPKZipFiles() {
    AsyncTask<Object, DownloadProgressInfo, Boolean> validationTask = new AsyncTask<Object, DownloadProgressInfo, Boolean>() {

        @Override
        protected void onPreExecute() {
            mDashboard.setVisibility(View.VISIBLE);
            mCellMessage.setVisibility(View.GONE);
            mStatusText.setText(R.string.text_verifying_download);
            mPauseButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mCancelValidation = true;
                }
            });
            mPauseButton.setText(R.string.text_button_cancel_verify);
            super.onPreExecute();
        }

        @Override
        protected Boolean doInBackground(Object... params) {
            for (XAPKFile xf : xAPKS) {
                String fileName = Helpers.getExpansionAPKFileName(SampleDownloaderActivity.this, xf.mIsMain,
                        xf.mFileVersion);
                if (!Helpers.doesFileExist(SampleDownloaderActivity.this, fileName, xf.mFileSize, false))
                    return false;
                fileName = Helpers.generateSaveFileName(SampleDownloaderActivity.this, fileName);
                ZipResourceFile zrf;
                byte[] buf = new byte[1024 * 256];
                try {
                    zrf = new ZipResourceFile(fileName);
                    ZipEntryRO[] entries = zrf.getAllEntries();
                    /**
                     * First calculate the total compressed length
                     */
                    long totalCompressedLength = 0;
                    for (ZipEntryRO entry : entries) {
                        totalCompressedLength += entry.mCompressedLength;
                    }
                    float averageVerifySpeed = 0;
                    long totalBytesRemaining = totalCompressedLength;
                    long timeRemaining;
                    /**
                     * Then calculate a CRC for every file in the
                     * Zip file, comparing it to what is stored in
                     * the Zip directory. Note that for compressed
                     * Zip files we must extract the contents to do
                     * this comparison.
                     */
                    for (ZipEntryRO entry : entries) {
                        if (-1 != entry.mCRC32) {
                            long length = entry.mUncompressedLength;
                            CRC32 crc = new CRC32();
                            DataInputStream dis = null;
                            try {
                                dis = new DataInputStream(zrf.getInputStream(entry.mFileName));

                                long startTime = SystemClock.uptimeMillis();
                                while (length > 0) {
                                    int seek = (int) (length > buf.length ? buf.length : length);
                                    dis.readFully(buf, 0, seek);
                                    crc.update(buf, 0, seek);
                                    length -= seek;
                                    long currentTime = SystemClock.uptimeMillis();
                                    long timePassed = currentTime - startTime;
                                    if (timePassed > 0) {
                                        float currentSpeedSample = (float) seek / (float) timePassed;
                                        if (0 != averageVerifySpeed) {
                                            averageVerifySpeed = SMOOTHING_FACTOR * currentSpeedSample
                                                    + (1 - SMOOTHING_FACTOR) * averageVerifySpeed;
                                        } else {
                                            averageVerifySpeed = currentSpeedSample;
                                        }
                                        totalBytesRemaining -= seek;
                                        timeRemaining = (long) (totalBytesRemaining / averageVerifySpeed);
                                        this.publishProgress(new DownloadProgressInfo(totalCompressedLength,
                                                totalCompressedLength - totalBytesRemaining, timeRemaining,
                                                averageVerifySpeed));
                                    }
                                    startTime = currentTime;
                                    if (mCancelValidation)
                                        return true;
                                }
                                if (crc.getValue() != entry.mCRC32) {
                                    Log.e(Constants.TAG, "CRC does not match for entry: " + entry.mFileName);
                                    Log.e(Constants.TAG, "In file: " + entry.getZipFileName());
                                    return false;
                                }
                            } finally {
                                if (null != dis) {
                                    dis.close();
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            }
            return true;
        }

        @Override
        protected void onProgressUpdate(DownloadProgressInfo... values) {
            onDownloadProgress(values[0]);
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (result) {
                mDashboard.setVisibility(View.VISIBLE);
                mCellMessage.setVisibility(View.GONE);
                mStatusText.setText(R.string.text_validation_complete);
                mPauseButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startMovie();
                    }
                });
                mPauseButton.setText(android.R.string.ok);
            } else {
                mDashboard.setVisibility(View.VISIBLE);
                mCellMessage.setVisibility(View.GONE);
                mStatusText.setText(R.string.text_validation_failed);
                mPauseButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        finish();
                    }
                });
                mPauseButton.setText(android.R.string.cancel);
            }
            super.onPostExecute(result);
        }

    };
    validationTask.execute(new Object());
}

From source file:org.mozilla.gecko.Tabs.java

public void handleMessage(String event, JSONObject message) {
    Log.i(LOGTAG, "Got message: " + event);
    try {/*  ww  w  . jav a  2s .c o  m*/
        if (event.startsWith("SessionHistory:")) {
            Tab tab = getTab(message.getInt("tabID"));
            if (tab != null) {
                event = event.substring("SessionHistory:".length());
                tab.handleSessionHistoryMessage(event, message);
            }
        } else if (event.equals("Tab:Added")) {
            Log.i(LOGTAG, "Received message from Gecko: " + SystemClock.uptimeMillis() + " - Tab:Added");
            Tab tab = addTab(message);
            if (message.getBoolean("selected"))
                selectTab(tab.getId());
            if (message.getBoolean("delayLoad"))
                tab.setHasLoaded(false);
        } else if (event.equals("Tab:Close")) {
            Tab tab = getTab(message.getInt("tabID"));
            closeTab(tab);
        } else if (event.equals("Tab:Select")) {
            selectTab(message.getInt("tabID"));
        } else if (event.equals("Session:RestoreBegin")) {
            mRestoringSession = true;
        } else if (event.equals("Session:RestoreEnd")) {
            mRestoringSession = false;
            GeckoApp.mAppContext.mMainHandler.post(new Runnable() {
                public void run() {
                    GeckoApp.mBrowserToolbar.updateTabCount(getCount());
                }
            });
        }
    } catch (Exception e) {
        Log.i(LOGTAG, "handleMessage throws " + e + " for message: " + event);
    }
}

From source file:com.ibm.pickmeup.activities.MapActivity.java

/**
 * Update map with the new coordinates for the driver
 * @param intent containing driver coordinates
 *//*from w  ww  .j a  v  a  2 s  . co m*/
private void updateMap(final Intent intent) {
    // not logging entry as it will flood the logs

    // getting driver LatLng values from the intent
    final LatLng driverLatLng = new LatLng(intent.getFloatExtra(Constants.LATITUDE, 0),
            intent.getFloatExtra(Constants.LONGITUDE, 0));

    // create driver marker if it doesn't exist and move the camera accordingly
    if (driverMarker == null) {
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(driverLatLng, 10));
        driverMarker = mMap.addMarker(new MarkerOptions().position(driverLatLng)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_driver)));
        return;
    }

    // update driver location with LatLng
    driverLocation.setLatitude(driverLatLng.latitude);
    driverLocation.setLongitude(driverLatLng.longitude);

    // calculate current distance to the passenger
    float distance = passengerLocation.distanceTo(driverLocation) / 1000;

    // set the distance text
    distanceDetails.setText(String.format(getResources().getString(R.string.distance_with_value), distance));

    // calculating ETA - we are assuming here that the car travels at 20mph to simplify the calculations
    calendar = Calendar.getInstance();
    calendar.add(Calendar.MINUTE, Math.round(distance / 20 * 60));

    // set AM/PM to a relevant value
    AM_PM = getString(R.string.am);
    if (calendar.get(Calendar.AM_PM) == 1) {
        AM_PM = getString(R.string.pm);
    }

    // format ETA string to HH:MM
    String eta = String.format(getResources().getString(R.string.eta_with_value),
            calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), AM_PM);

    // set the ETA text
    etaDetails.setText(eta);

    // as we are throttling updates to the coordinates, we might need to smooth out the moving
    // of the driver's marker. To do so we are going to draw temporary markers between the
    // previous and the current coordinates. We are going to use interpolation for this and
    // use handler/looper to set the marker's position

    // get hold of the handler
    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();

    // get map projection and the driver's starting point
    Projection proj = mMap.getProjection();
    Point startPoint = proj.toScreenLocation(driverMarker.getPosition());
    final LatLng startLatLng = proj.fromScreenLocation(startPoint);
    final long duration = 150;

    // create new Interpolator
    final Interpolator interpolator = new LinearInterpolator();

    // post a Runnable to the handler
    handler.post(new Runnable() {
        @Override
        public void run() {
            // calculate how soon we need to redraw the marker
            long elapsed = SystemClock.uptimeMillis() - start;
            float t = interpolator.getInterpolation((float) elapsed / duration);
            double lng = t * intent.getFloatExtra(Constants.LONGITUDE, 0) + (1 - t) * startLatLng.longitude;
            double lat = t * intent.getFloatExtra(Constants.LATITUDE, 0) + (1 - t) * startLatLng.latitude;

            // set the driver's marker position
            driverMarker.setPosition(new LatLng(lat, lng));
            if (t < 1.0) {
                handler.postDelayed(this, 10);
            }
        }
    });
}

From source file:com.barkside.travellocblog.LocationUpdates.java

/**
 * The concrete subclass needs to turn on/off the location updates.
 * Call this in an onCreate or onStart to enable the receipt of location updates.
 * By the time an onConnected event is called, this must be set correctly to attach
 * the LocationRequest object to the LocationClient.
 * Note that to actually stop updates, call stopLocationUpdates().
 * //from ww w. ja  v  a 2s  .  c o  m
 * @param durationSecs how long to look for location updates
 */
protected void enableLocationUpdates(int durationSecs) {
    mUpdatesRequested = true;
    mUpdatesDurationSecs = durationSecs;

    // Compute the expiration time as now + durationSecs.
    // We don't use durationSecs if mExpirationTime is already known - which happens
    // when this activity is recreated on a screen orientation change, etc.
    if (mUpdatesDurationSecs != mNoAutoOff && mExpirationTime == 0) {
        long durationMillis = Math.abs(durationSecs) * MILLISECONDS_PER_SECOND;
        mExpirationTime = SystemClock.uptimeMillis() + durationMillis;
    }

    if (durationSecs > 0 && mLocationClient != null) {
        Log.d(TAG, "Starting location timer for seconds: " + durationSecs);
        Log.d(TAG, "Starting location timer to time: " + mExpirationTime);

        // Location Updates are to expire at given time
        // Since this is exact time, this is not affected by screen orientation changes,
        // it will not restart timer. This will be affected if phone goes to sleep, since
        // uptimeMillis does not advance in that case. If mExpirationTime is less than
        // current uptimeMillis, it means no location updates will be received.
        //
        // Since we may be called multiple times in case caller has to turn on/off location
        // updates multiple times, for each enable call we set the time again, and
        // we make sure to remove old callbacks before we add a new one.
        timerHandler.removeCallbacks(timerEvent);
        timerHandler.postAtTime(timerEvent, mExpirationTime);

        // mLocationRequest.setExpirationDuration(durationSecs * MILLISECONDS_PER_SECOND); 
        // Not using setExpirationDuration since we may be called multiple times, and
        // need to keep resetting the duration, which can't be done with setExpirationDuration
        // More importantly, we need to know when the timer has stopped, so we can update
        // the location, or print a message, as is done in the run() method.

        if (mLocationClient.isConnected()) {
            // Most likely we have not received a onConnected event but if we have,
            // we need to start up the updates again, in case they are no longer active.
            // This can be called multiple times - if called again, will just replace
            // the old listener with "this" object as per the API doc.
            mLocationClient.requestLocationUpdates(mLocationRequest, this);
        }
    }
}

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

@Override
public boolean onTouchEvent(@NonNull MotionEvent me) {
    if (getKeyboard() == null)//I mean, if there isn't any keyboard I'm handling, what's the point?
        return false;

    if (areTouchesDisabled(me)) {
        return super.onTouchEvent(me);
    }/*from w w  w.  j  a va  2s  .  co  m*/

    final int action = MotionEventCompat.getActionMasked(me);

    // Gesture detector must be enabled only when mini-keyboard is not
    // on the screen.
    if (!mMiniKeyboardPopup.isShowing() && mGestureDetector != null && mGestureDetector.onTouchEvent(me)) {
        Logger.d(TAG, "Gesture detected!");
        mKeyPressTimingHandler.cancelAllMessages();
        dismissAllKeyPreviews();
        return true;
    }

    if (action == MotionEvent.ACTION_DOWN) {
        mFirstTouchPoint.x = (int) me.getX();
        mFirstTouchPoint.y = (int) me.getY();
        mIsFirstDownEventInsideSpaceBar = mSpaceBarKey != null
                && mSpaceBarKey.isInside(mFirstTouchPoint.x, mFirstTouchPoint.y);
    }
    // If the motion event is above the keyboard and it's a MOVE event
    // coming even before the first MOVE event into the extension area
    if (!mIsFirstDownEventInsideSpaceBar && me.getY() < mExtensionKeyboardYActivationPoint
            && !mMiniKeyboardPopup.isShowing() && !mExtensionVisible && action == MotionEvent.ACTION_MOVE) {
        if (mExtensionKeyboardAreaEntranceTime <= 0)
            mExtensionKeyboardAreaEntranceTime = SystemClock.uptimeMillis();

        if (SystemClock.uptimeMillis()
                - mExtensionKeyboardAreaEntranceTime > DELAY_BEFORE_POPPING_UP_EXTENSION_KBD) {
            KeyboardExtension extKbd = ((ExternalAnyKeyboard) getKeyboard()).getExtensionLayout();
            if (extKbd == null || extKbd.getKeyboardResId() == AddOn.INVALID_RES_ID) {
                Logger.i(TAG, "No extension keyboard");
                return super.onTouchEvent(me);
            } else {
                // telling the main keyboard that the last touch was
                // canceled
                MotionEvent cancel = MotionEvent.obtain(me.getDownTime(), me.getEventTime(),
                        MotionEvent.ACTION_CANCEL, me.getX(), me.getY(), 0);
                super.onTouchEvent(cancel);
                cancel.recycle();

                mExtensionVisible = true;
                dismissAllKeyPreviews();
                if (mExtensionKey == null) {
                    mExtensionKey = new AnyKey(new Row(getKeyboard()), getThemedKeyboardDimens());
                    mExtensionKey.edgeFlags = 0;
                    mExtensionKey.height = 1;
                    mExtensionKey.width = 1;
                    mExtensionKey.popupResId = extKbd.getKeyboardResId();
                    mExtensionKey.externalResourcePopupLayout = mExtensionKey.popupResId != 0;
                    mExtensionKey.x = getWidth() / 2;
                    mExtensionKey.y = mExtensionKeyboardPopupOffset;
                }
                // so the popup will be right above your finger.
                mExtensionKey.x = (int) me.getX();

                onLongPress(extKbd, mExtensionKey, AnyApplication.getConfig().isStickyExtensionKeyboard(),
                        getPointerTracker(me));
                // it is an extension..
                getMiniKeyboard().setPreviewEnabled(true);
                return true;
            }
        } else {
            return super.onTouchEvent(me);
        }
    } else if (mExtensionVisible && me.getY() > mExtensionKeyboardYDismissPoint) {
        // closing the popup
        dismissPopupKeyboard();
        return true;
    } else {
        return super.onTouchEvent(me);
    }
}

From source file:com.microsoft.office.integration.test.AbstractTest.java

private boolean waitForAdalActivity(long timeout) {
    final long endTime = SystemClock.uptimeMillis() + timeout;

    while (SystemClock.uptimeMillis() < endTime) {
        Activity activity = activityMonitor.getLastActivity();
        // Wait for authentication activity (not the test activity).
        if ((activity != null) && !(activity instanceof TestActivity)) {
            adalActivity = activity;/*from www.  ja  v a 2s.c o m*/
            return true;
        }
        try {
            Thread.sleep(SMALL_DELAY);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    adalActivity = null;
    return false;
}

From source file:com.box.androidlib.BoxFileDownload.java

/**
 * Execute a file download.// w  w w . j  av  a2 s.c  o m
 * 
 * @param fileId
 *            The file_id of the file to be downloaded
 * @param destinationOutputStreams
 *            OutputStreams to which the data should be written to as it is downloaded.
 * @param versionId
 *            The version_id of the version of the file to download. Set to null to download the latest version of the file.
 * @return a response handler
 * @throws IOException
 *             Can be thrown if there was a connection error, or if destination file could not be written.
 */
public DefaultResponseParser execute(final long fileId, final OutputStream[] destinationOutputStreams,
        final Long versionId) throws IOException {

    final DefaultResponseParser handler = new DefaultResponseParser();

    final Uri.Builder builder = new Uri.Builder();
    builder.scheme(BoxConfig.getInstance().getDownloadUrlScheme());
    builder.encodedAuthority(BoxConfig.getInstance().getDownloadUrlAuthority());
    builder.path(BoxConfig.getInstance().getDownloadUrlPath());
    builder.appendPath(mAuthToken);
    builder.appendPath(String.valueOf(fileId));
    if (versionId != null) {
        builder.appendPath(String.valueOf(versionId));
    }

    List<BasicNameValuePair> customQueryParams = BoxConfig.getInstance().getCustomQueryParameters();
    if (customQueryParams != null && customQueryParams.size() > 0) {
        for (BasicNameValuePair param : customQueryParams) {
            builder.appendQueryParameter(param.getName(), param.getValue());
        }
    }

    // We normally prefer to use HttpUrlConnection, however that appears to fail for certain types of files. For downloads, it appears DefaultHttpClient
    // works more reliably.
    final DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpProtocolParams.setUserAgent(httpclient.getParams(), BoxConfig.getInstance().getUserAgent());
    HttpGet httpGet;

    String theUri = builder.build().toString();
    if (BoxConfig.getInstance().getHttpLoggingEnabled()) {
        //DevUtils.logcat("User-Agent : " + HttpProtocolParams.getUserAgent(httpclient.getParams()));
        DevUtils.logcat("Box Request: " + theUri);
    }
    try {
        httpGet = new HttpGet(new URI(theUri));
    } catch (URISyntaxException e) {
        throw new IOException("Invalid Download URL");
    }
    httpGet.setHeader("Connection", "close");
    httpGet.setHeader("Accept-Language", BoxConfig.getInstance().getAcceptLanguage());
    HttpResponse httpResponse = httpclient.execute(httpGet);

    int responseCode = httpResponse.getStatusLine().getStatusCode();

    if (BoxConfig.getInstance().getHttpLoggingEnabled()) {
        DevUtils.logcat("Box Response: " + responseCode);
        //            Header[] headers = httpResponse.getAllHeaders();
        //            for (Header header : headers) {
        //                DevUtils.logcat("Response Header: " + header.toString());
        //            }
    }

    // Server returned a 503 Service Unavailable. Usually means a temporary unavailability.
    if (responseCode == HttpStatus.SC_SERVICE_UNAVAILABLE) {
        //            if (BoxConfig.getInstance().getHttpLoggingEnabled()) {
        //                DevUtils.logcat("HTTP Response Code: " + HttpStatus.SC_SERVICE_UNAVAILABLE);
        //            }
        handler.setStatus(ResponseListener.STATUS_SERVICE_UNAVAILABLE);
        return handler;
    }

    InputStream is = httpResponse.getEntity().getContent();
    if (responseCode == HttpURLConnection.HTTP_OK) {
        // Grab the first 100 bytes and check for an error string.
        // Not a good way for the server to respond with errors but that's the way it is for now.
        final byte[] errorCheckBuffer = new byte[FILE_ERROR_SIZE];
        // Three cases here: error, no error && file size == 0, no error && file size > 0.
        // The first case will be handled by parsing the error check buffer. The second case will result in mBytesTransferred == 0,
        // no real bytes will be transferred but we still treat as success case. The third case is normal success case.
        mBytesTransferred = Math.max(0, is.read(errorCheckBuffer));
        final String str = new String(errorCheckBuffer).trim();
        if (str.equals(FileDownloadListener.STATUS_DOWNLOAD_WRONG_AUTH_TOKEN)) {
            handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_WRONG_AUTH_TOKEN);
        } else if (str.equals(FileDownloadListener.STATUS_DOWNLOAD_RESTRICTED)) {
            handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_RESTRICTED);
        }
        // No error detected
        else {
            // Copy the file to destination if > 0 bytes of file transferred.
            if (mBytesTransferred > 0) {
                for (int i = 0; i < destinationOutputStreams.length; i++) {
                    destinationOutputStreams[i].write(errorCheckBuffer, 0, (int) mBytesTransferred); // Make sure we don't lose that first 100 bytes.
                }

                // Read the rest of the stream and write to the destination OutputStream.
                final byte[] buffer = new byte[DOWNLOAD_BUFFER_SIZE];
                int bufferLength = 0;
                long lastOnProgressPost = 0;
                while (!Thread.currentThread().isInterrupted() && (bufferLength = is.read(buffer)) > 0) {
                    for (int i = 0; i < destinationOutputStreams.length; i++) {
                        destinationOutputStreams[i].write(buffer, 0, bufferLength);
                    }
                    mBytesTransferred += bufferLength;
                    long currTime = SystemClock.uptimeMillis();
                    if (mListener != null && mHandler != null
                            && currTime - lastOnProgressPost > ON_PROGRESS_UPDATE_THRESHOLD) {
                        lastOnProgressPost = currTime;
                        mHandler.post(mOnProgressRunnable);
                    }
                }
                mHandler.post(mOnProgressRunnable);
            }
            for (int i = 0; i < destinationOutputStreams.length; i++) {
                destinationOutputStreams[i].close();
            }
            handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_OK);

            // If download thread was interrupted, set to
            // STATUS_DOWNLOAD_CANCELED
            if (Thread.currentThread().isInterrupted()) {
                httpGet.abort();
                handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_CANCELLED);
            }
        }
    } else if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
        handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_PERMISSIONS_ERROR);
    } else {
        handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_FAIL);
    }
    httpResponse.getEntity().consumeContent();
    if (httpclient != null && httpclient.getConnectionManager() != null) {
        httpclient.getConnectionManager().closeIdleConnections(500, TimeUnit.MILLISECONDS);
    }
    is.close();

    return handler;
}

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

private static void logExecutionTime(String name, long time) {
    if (LibraryLoader.isInitialized()) {
        RecordHistogram.recordTimesHistogram("Android.StrictMode.TabPersistentStore." + name,
                SystemClock.uptimeMillis() - time, TimeUnit.MILLISECONDS);
    }//from  ww w.j  a  va2  s.  c o  m
}