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.adw.library.widgets.discreteseekbar.internal.drawable.MarkerDrawable.java

public void animateToPressed() {
    unscheduleSelf(mUpdater);//from   ww  w .  j a  v a2 s. com
    mReverse = false;
    if (mCurrentScale < 1) {
        mRunning = true;
        mAnimationInitialValue = mCurrentScale;
        float durationFactor = 1f - mCurrentScale;
        mDuration = (int) (ANIMATION_DURATION * durationFactor);
        mStartTime = SystemClock.uptimeMillis();
        scheduleSelf(mUpdater, mStartTime + FRAME_DURATION);
    } else {
        notifyFinishedToListener();
    }
}

From source file:com.mycompany.myfirstindoorsapp.PagedActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.pointMode:
        item.setChecked(true);/*from   ww  w. j a va  2 s .co  m*/
        mesureMode = POINTMODE;
        createdOverlays = refreshOverlay(createdOverlays);
        twoPoints[0] = null;
        twoPoints[1] = null;
        singlePoint = null;
        return true;
    case R.id.lineMode:
        item.setChecked(true);
        mesureMode = LINEMODE;
        createdOverlays = refreshOverlay(createdOverlays);
        twoPoints[0] = null;
        twoPoints[1] = null;
        singlePoint = null;
        return true;
    case R.id.menu_startMesurement:
        // begin mesurement
        if ((currentPosition == null) || ((singlePoint == null) && (twoPoints[0] == null))) {
            Toast.makeText(this, "Set pts", Toast.LENGTH_SHORT).show();
        } else {

            double[] coord = new double[4];
            coord[0] = currentPosition.x;
            coord[1] = currentPosition.y;
            coord[2] = 0;
            coord[3] = 0;
            RealVector x = new ArrayRealVector(coord);
            kalman = new Kalman(accelNoise, measurementNoise, x);
            accel.start(mesureMode);
            if ((mesureMode == POINTMODE) && (singlePoint != null)) {
                data = new Data(singlePoint);
                Toast.makeText(this, "new Data (singlePoint)", Toast.LENGTH_SHORT).show();
            }
            if ((mesureMode == LINEMODE) && (twoPoints[0] != null) && (twoPoints[1] != null)) {
                data = new Data(twoPoints[0], twoPoints[1], SystemClock.uptimeMillis());
                Toast.makeText(this, "new Data (twoPoints)", Toast.LENGTH_SHORT).show();
            }
            if ((twoPoints[0] != null) && (twoPoints[1] != null) && (singlePoint != null)) {
                Toast.makeText(this, "singlePoint!=!=!null!=!=!twoPoints[0][1]", Toast.LENGTH_SHORT).show();
            }
            if ((twoPoints[0] == null) && (twoPoints[1] == null) && (singlePoint == null)) {
                Toast.makeText(this, "singlePoint==null==twoPoints[0][1]", Toast.LENGTH_SHORT).show();
            }
        }
        return true;
    case R.id.menu_stopMesurement:
        if (null != data) {
            double[] standartDeviations = data.calc(SystemClock.uptimeMillis());
            accel.stop();
            kalman = null;
            fragment.addItem(pagedActivity, indoorsSurfaceFragment, "Deviation for indoors="
                    + standartDeviations[0] + "; and for Kalman=" + standartDeviations[1],
                    new Coordinate(0, 0, 0));

            Toast.makeText(this, "Deviation for indoors=" + standartDeviations[0] + "; and for " + "Kalman="
                    + standartDeviations[1], Toast.LENGTH_LONG).show();
            data = null;
            if (overlayKalman != null) {
                indoorsSurfaceFragment.removeOverlay(overlayKalman);
                indoorsSurfaceFragment.updateSurface();
            }
        }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:org.adw.library.widgets.discreteseekbar.internal.drawable.AlmostRippleDrawable.java

public void animateToPressed() {
    unscheduleSelf(mUpdater);/*from  w w w .  j a va 2  s . c o  m*/
    if (mCurrentScale < ACTIVE_SCALE) {
        mReverse = false;
        mRunning = true;
        mAnimationInitialValue = mCurrentScale;
        float durationFactor = 1f
                - ((mAnimationInitialValue - INACTIVE_SCALE) / (ACTIVE_SCALE - INACTIVE_SCALE));
        mDuration = (int) (ANIMATION_DURATION * durationFactor);
        mStartTime = SystemClock.uptimeMillis();
        scheduleSelf(mUpdater, mStartTime + FRAME_DURATION);
    }
}

From source file:com.haoqee.chat.global.VoiceTask.java

private void handleResponse(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    if (status.getStatusCode() >= 300) {
        String errorMsg = "response status error code:" + status.getStatusCode();
        if (status.getStatusCode() == 416 && isResume) {
            errorMsg += " \n maybe you have download complete.";
        }// w w w.  j  ava 2 s .c  om
        publishProgress(UPDATE_FAILURE,
                new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), errorMsg);
    } else {
        try {
            HttpEntity entity = response.getEntity();
            Object responseBody = null;
            if (entity != null) {
                time = SystemClock.uptimeMillis();
                if (targetUrl != null) {
                    responseBody = mFileEntityHandler.handleEntity(entity, this, targetUrl, isResume);
                } else {
                    responseBody = mStrEntityHandler.handleEntity(entity, this, charset);
                }

            }
            publishProgress(UPDATE_SUCCESS, responseBody);

        } catch (IOException e) {
            publishProgress(UPDATE_FAILURE, e, e.getMessage());
        }

    }
}

From source file:com.shizhefei.view.largeimage.ImageManager.java

/**
 * @param imageScale width/?width imageScale = 4400???100?<br>
 *                   imageScale??position?blockSize?<br>
 *                   blockSize*imageScale?,
 *                   imageScale??positionblockSize
 *///from  ww w. ja v a 2s.com
public List<DrawData> getDrawData(float imageScale, Rect imageRect) {
    long startTime = SystemClock.uptimeMillis();
    LoadData loadData = mLoadData;
    if (loadData == null || loadData.mDecoder == null) {
        return new ArrayList<DrawData>(0);
    }
    int imageWidth = loadData.mImageWidth;
    int imageHeight = loadData.mImageHeight;
    List<CacheData> cacheDatas = loadData.mCacheDatas;
    Bitmap cacheImageData = loadData.mCacheImageData;
    int cacheImageScale = loadData.mCacheImageScale;

    List<DrawData> drawDatas = new ArrayList<DrawData>();
    if (imageRect.left < 0) {
        imageRect.left = 0;
    }
    if (imageRect.top < 0) {
        imageRect.top = 0;
    }
    if (imageRect.right > loadData.mImageWidth) {
        imageRect.right = loadData.mImageWidth;
    }
    if (imageRect.bottom > loadData.mImageHeight) {
        imageRect.bottom = loadData.mImageHeight;
    }

    if (cacheImageData == null) {
        try {
            int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
            int screenHeight = context.getResources().getDisplayMetrics().heightPixels;
            int s = (int) Math.sqrt(imageWidth * imageHeight / (screenWidth / 2) / (screenHeight / 2));
            cacheImageScale = getNearScale(s);
            if (cacheImageScale < s) {
                cacheImageScale *= 2;
            }
            handler.sendMessage(handler.obtainMessage(MESSAGE_PIC, cacheImageScale));
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        Rect cacheImageRect = new Rect(imageRect);
        int cache = dip2px(context, 100);
        cache = (int) (cache * imageScale);
        cacheImageRect.right += cache;
        cacheImageRect.top -= cache;
        cacheImageRect.left -= cache;
        cacheImageRect.bottom += cache;

        if (cacheImageRect.left < 0) {
            cacheImageRect.left = 0;
        }
        if (cacheImageRect.top < 0) {
            cacheImageRect.top = 0;
        }
        if (cacheImageRect.right > imageWidth) {
            cacheImageRect.right = imageWidth;
        }
        if (cacheImageRect.bottom > imageHeight) {
            cacheImageRect.bottom = imageHeight;
        }
        Rect r = new Rect();
        r.left = (int) Math.abs(1.0f * cacheImageRect.left / cacheImageScale);
        r.right = (int) Math.abs(1.0f * cacheImageRect.right / cacheImageScale);
        r.top = (int) Math.abs(1.0f * cacheImageRect.top / cacheImageScale);
        r.bottom = (int) Math.abs(1.0f * cacheImageRect.bottom / cacheImageScale);
        drawDatas.add(new DrawData(cacheImageData, r, cacheImageRect));

        Log.d("vvvv", "imageRect:" + imageRect + " tempImageScale:" + cacheImageScale);
        Log.d("vvvv", "rect:" + r);
    }
    int scale = getNearScale(imageScale);
    if (cacheImageScale <= scale && cacheImageData != null) {
        return drawDatas;
    }
    // if (true) {
    // return drawDatas;
    // }
    Log.d("dddd", "scale: " + scale);
    int blockSize = BASE_BLOCKSIZE * scale;
    int maxRow = imageHeight / blockSize + (imageHeight % blockSize == 0 ? 0 : 1);
    int maxCol = imageWidth / blockSize + (imageWidth % blockSize == 0 ? 0 : 1);

    // scaleposition
    int startRow = imageRect.top / blockSize + (imageRect.top % blockSize == 0 ? 0 : 1) - 1;
    int endRow = imageRect.bottom / blockSize + (imageRect.bottom % blockSize == 0 ? 0 : 1);
    int startCol = imageRect.left / blockSize + (imageRect.left % blockSize == 0 ? 0 : 1) - 1;
    int endCol = imageRect.right / blockSize + (imageRect.right % blockSize == 0 ? 0 : 1);
    if (startRow < 0) {
        startRow = 0;
    }
    if (startCol < 0) {
        startCol = 0;
    }
    if (endRow > maxRow) {
        endRow = maxRow;
    }
    if (endCol > maxCol) {
        endCol = maxCol;
    }

    int cacheStartRow = startRow - 1;
    int cacheEndRow = endRow + 1;
    int cacheStartCol = startCol - 1;
    int cacheEndCol = endCol + 1;
    if (cacheStartRow < 0) {
        cacheStartRow = 0;
    }
    if (cacheStartCol < 0) {
        cacheStartCol = 0;
    }
    if (cacheEndRow > maxRow) {
        cacheEndRow = maxRow;
    }
    if (cacheEndCol > maxCol) {
        cacheEndCol = maxCol;
    }

    Log.d("countTime", "preTime :" + (SystemClock.uptimeMillis() - startTime));
    startTime = SystemClock.uptimeMillis();

    Set<Position> needShowPositions = new HashSet<Position>();

    // ?
    handler.removeMessages(preMessageWhat);
    int what = preMessageWhat == MESSAGE_BLOCK_1 ? MESSAGE_BLOCK_2 : MESSAGE_BLOCK_1;
    preMessageWhat = what;

    if (loadData.mCurrentCacheData != null && loadData.mCurrentCacheData.scale != scale) {
        cacheDatas.add(new CacheData(loadData.mCurrentCacheData.scale,
                new HashMap<Position, Bitmap>(loadData.mCurrentCacheData.images)));
        loadData.mCurrentCacheData = null;
    }
    if (loadData.mCurrentCacheData == null) {
        Iterator<CacheData> iterator = cacheDatas.iterator();
        while (iterator.hasNext()) {
            CacheData cacheData = iterator.next();
            if (scale == cacheData.scale) {
                loadData.mCurrentCacheData = new CacheData(scale,
                        new ConcurrentHashMap<Position, Bitmap>(cacheData.images));
                iterator.remove();
            }
        }
    }
    if (loadData.mCurrentCacheData == null) {
        loadData.mCurrentCacheData = new CacheData(scale, new ConcurrentHashMap<Position, Bitmap>());
        for (int row = startRow; row <= endRow; row++) {
            for (int col = startCol; col <= endCol; col++) {
                Position position = new Position(row, col);
                needShowPositions.add(position);
                handler.sendMessage(handler.obtainMessage(what, new MessageData(position, scale)));
            }
        }

        /**
         * <pre>
         * #########  1
         * #       #
         * #       #
         * #########
         *
         * <pre>
         */

        //  #########
        for (int row = cacheStartRow; row < startRow; row++) {
            for (int col = cacheStartCol; col <= cacheEndCol; col++) {
                Position position = new Position(row, col);
                handler.sendMessage(handler.obtainMessage(what, new MessageData(position, scale)));
            }
        }
        //  #########
        for (int row = endRow + 1; row < cacheEndRow; row++) {
            for (int col = cacheStartCol; col <= cacheEndCol; col++) {
                Position position = new Position(row, col);
                handler.sendMessage(handler.obtainMessage(what, new MessageData(position, scale)));
            }
        }
        // # 
        // #
        for (int row = startRow; row < endRow; row++) {
            for (int col = cacheStartCol; col < startCol; col++) {
                Position position = new Position(row, col);
                handler.sendMessage(handler.obtainMessage(what, new MessageData(position, scale)));
            }
        }
        // # ?
        // #
        for (int row = startRow; row < endRow; row++) {
            for (int col = endRow + 1; col < cacheEndRow; col++) {
                Position position = new Position(row, col);
                handler.sendMessage(handler.obtainMessage(what, new MessageData(position, scale)));
            }
        }
    } else {
        /*
         * scale?position
        */
        Set<Position> usePositions = new HashSet<ImageManager.Position>();
        for (int row = startRow; row <= endRow; row++) {
            for (int col = startCol; col <= endCol; col++) {
                Position position = new Position(row, col);
                Bitmap bitmap = loadData.mCurrentCacheData.images.get(position);
                if (bitmap == null) {
                    needShowPositions.add(position);
                    handler.sendMessage(handler.obtainMessage(what, new MessageData(position, scale)));
                } else {
                    usePositions.add(position);
                    Rect rect = madeRect(bitmap, row, col, scale, imageScale);
                    drawDatas.add(new DrawData(bitmap, null, rect));
                }
            }
        }
        //  #########
        for (int row = cacheStartRow; row < startRow; row++) {
            for (int col = cacheStartCol; col <= cacheEndCol; col++) {
                Position position = new Position(row, col);
                usePositions.add(position);
                handler.sendMessage(handler.obtainMessage(what, new MessageData(position, scale)));
            }
        }
        //  #########
        for (int row = endRow + 1; row < cacheEndRow; row++) {
            for (int col = cacheStartCol; col <= cacheEndCol; col++) {
                Position position = new Position(row, col);
                usePositions.add(position);
                Log.d("9999", " " + position);
                handler.sendMessage(handler.obtainMessage(what, new MessageData(position, scale)));
            }
        }
        // # 
        // #
        for (int row = startRow; row < endRow; row++) {
            for (int col = cacheStartCol; col < startCol; col++) {
                Position position = new Position(row, col);
                usePositions.add(position);
                handler.sendMessage(handler.obtainMessage(what, new MessageData(position, scale)));
            }
        }
        // # ?
        // #
        for (int row = startRow; row < endRow; row++) {
            for (int col = endRow + 1; col < cacheEndRow; col++) {
                Position position = new Position(row, col);
                usePositions.add(position);
                handler.sendMessage(handler.obtainMessage(what, new MessageData(position, scale)));
            }
        }
        loadData.mCurrentCacheData.images.keySet().retainAll(usePositions);
    }

    Log.d("countTime", "currentScale time :" + (SystemClock.uptimeMillis() - startTime));
    startTime = SystemClock.uptimeMillis();

    //
    if (!needShowPositions.isEmpty()) {
        Collections.sort(cacheDatas, new NearComparator(scale));
        Iterator<CacheData> iterator = cacheDatas.iterator();
        while (iterator.hasNext()) {
            CacheData cacheData = iterator.next();
            int scaleKey = cacheData.scale;
            if (scaleKey / scale == 2) {// scale.,???

                Log.d("countTime", ",? time :" + (SystemClock.uptimeMillis() - startTime));
                startTime = SystemClock.uptimeMillis();

                int ds = scaleKey / scale;

                // ??
                int size = scale * BASE_BLOCKSIZE;

                // 
                int startRowKey = cacheStartRow / 2;
                int endRowKey = cacheEndRow / 2;
                int startColKey = cacheStartCol / 2;
                int endColKey = cacheEndCol / 2;

                Iterator<Entry<Position, Bitmap>> imageiterator = cacheData.images.entrySet().iterator();
                while (imageiterator.hasNext()) {
                    Entry<Position, Bitmap> entry = imageiterator.next();
                    Position position = entry.getKey();
                    if (!(startRowKey <= position.row && position.row <= endRowKey
                            && startColKey <= position.col && position.col <= endColKey)) {
                        imageiterator.remove();
                    }
                }

                Iterator<Entry<Position, Bitmap>> imagesIterator = cacheData.images.entrySet().iterator();
                while (imagesIterator.hasNext()) {
                    Entry<Position, Bitmap> entry = imagesIterator.next();
                    Position position = entry.getKey();
                    int startPositionRow = position.row * ds;
                    int endPositionRow = startPositionRow + ds;
                    int startPositionCol = position.col * ds;
                    int endPositionCol = startPositionCol + ds;
                    Bitmap bitmap = entry.getValue();
                    int iW = bitmap.getWidth();
                    int iH = bitmap.getHeight();

                    // ???
                    int blockImageSize = BASE_BLOCKSIZE / ds;

                    Log.d("nnnn", " bitmap.getWidth():" + bitmap.getWidth() + " imageHeight:" + iH);
                    for (int row = startPositionRow, i = 0; row <= endPositionRow; row++, i++) {
                        int top = i * blockImageSize;
                        if (top >= iH) {
                            break;
                        }
                        for (int col = startPositionCol, j = 0; col <= endPositionCol; col++, j++) {
                            int left = j * blockImageSize;
                            if (left >= iW) {
                                break;
                            }
                            if (needShowPositions.remove(new Position(row, col))) {
                                int right = left + blockImageSize;
                                int bottom = top + blockImageSize;
                                if (right > iW) {
                                    right = iW;
                                }
                                if (bottom > iH) {
                                    bottom = iH;
                                }
                                Rect rect = new Rect();
                                rect.left = col * size;
                                rect.top = row * size;
                                rect.right = rect.left + (right - left) * scaleKey;
                                rect.bottom = rect.top + (bottom - top) * scaleKey;
                                drawDatas.add(new DrawData(bitmap, new Rect(left, top, right, bottom), rect));
                            }
                        }
                    }
                }

                Log.d("countTime", ",? time :" + (SystemClock.uptimeMillis() - startTime));
            } else if (scale / scaleKey == 2) {// ???
                int size = scaleKey * BASE_BLOCKSIZE;

                Log.d("countTime", "   time :" + (SystemClock.uptimeMillis() - startTime));
                startTime = SystemClock.uptimeMillis();

                int startRowKey = imageRect.top / size + (imageRect.top % size == 0 ? 0 : 1) - 1;
                int endRowKey = imageRect.bottom / size + (imageRect.bottom % size == 0 ? 0 : 1);
                int startColKey = imageRect.left / size + (imageRect.left % size == 0 ? 0 : 1) - 1;
                int endColKey = imageRect.right / size + (imageRect.right % size == 0 ? 0 : 1);

                Log.d("nnnn",
                        "startRowKey" + startRowKey + " endRowKey:+" + endRowKey + " endColKey:" + endColKey);

                Position tempPosition = new Position();
                Iterator<Entry<Position, Bitmap>> imageiterator = cacheData.images.entrySet().iterator();
                while (imageiterator.hasNext()) {
                    Entry<Position, Bitmap> entry = imageiterator.next();
                    Position position = entry.getKey();
                    if (!(startRowKey <= position.row && position.row <= endRowKey
                            && startColKey <= position.col && position.col <= endColKey)) {
                        imageiterator.remove();
                        Log.d("nnnn", "position:" + position + " remove");
                    } else {
                        Bitmap bitmap = entry.getValue();
                        tempPosition.set(position.row / 2 + (position.row % 2 == 0 ? 0 : 1),
                                position.col / 2 + (position.col % 2 == 0 ? 0 : 1));
                        if (needShowPositions.contains(tempPosition)) {
                            Rect rect = new Rect();
                            rect.left = position.col * size;
                            rect.top = position.row * size;
                            rect.right = rect.left + bitmap.getWidth() * scaleKey;
                            rect.bottom = rect.top + bitmap.getHeight() * scaleKey;
                            drawDatas.add(new DrawData(bitmap, null, rect));
                        }
                    }
                }

                Log.d("countTime", "   time :" + (SystemClock.uptimeMillis() - startTime));
                startTime = SystemClock.uptimeMillis();
            } else {
                iterator.remove();
            }
        }
    }
    return drawDatas;
}

From source file:com.kohoh.AsyncTaskLoader.java

void dispatchOnCancelled(LoadTask task, D data) {
    onCanceled(data);/*from  ww w  .  j av a2s . c  om*/
    if (mCancellingTask == task) {
        if (DEBUG)
            Log.v(TAG, "Cancelled task is now canceled!");
        rollbackContentChanged();
        mLastLoadCompleteTime = SystemClock.uptimeMillis();
        mCancellingTask = null;
        executePendingTask();
    }
}

From source file:org.adw.library.widgets.discreteseekbar.internal.drawable.MarkerDrawable.java

public void animateToNormal() {
    mReverse = true;//from   w  ww  .  j  a va2 s. co  m
    unscheduleSelf(mUpdater);
    if (mCurrentScale > 0) {
        mRunning = true;
        mAnimationInitialValue = mCurrentScale;
        float durationFactor = 1f - mCurrentScale;
        mDuration = ANIMATION_DURATION - (int) (ANIMATION_DURATION * durationFactor);
        mStartTime = SystemClock.uptimeMillis();
        scheduleSelf(mUpdater, mStartTime + FRAME_DURATION);
    } else {
        notifyFinishedToListener();
    }
}

From source file:io.appium.uiautomator2.core.AccessibilityNodeInfoDumper.java

private InputStream toStream() throws IOException {
    final long startTime = SystemClock.uptimeMillis();
    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
        serializer = Xml.newSerializer();
        shouldAddDisplayInfo = root == null;
        serializer.setOutput(outputStream, XML_ENCODING);
        serializer.startDocument(XML_ENCODING, true);
        serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
        final UiElement<?, ?> xpathRoot = root == null
                ? rebuildForNewRoot(currentActiveWindowRoot(),
                        NotificationListener.getInstance().getToastMessage())
                : rebuildForNewRoot(root, null);
        serializeUiElement(xpathRoot, 0);
        serializer.endDocument();/*from  w ww.ja va 2  s .c  o  m*/
        Logger.debug(String.format("The source XML tree (%s bytes) has been fetched in %sms",
                outputStream.size(), SystemClock.uptimeMillis() - startTime));
        return new ByteArrayInputStream(outputStream.toByteArray());
    }
}

From source file:com.adis.tools.http.HttpHandler.java

@Override
protected Void doInBackground(Object... params) {
    if (this.state == State.CANCELLED || params == null || params.length == 0)
        return null;

    if (params.length > 3) {
        fileSavePath = String.valueOf(params[1]);
        isDownloadingFile = fileSavePath != null;
        autoResume = (Boolean) params[2];
        autoRename = (Boolean) params[3];
    }/*w  w  w.  java 2 s  .  co  m*/

    try {
        if (this.state == State.CANCELLED)
            return null;
        // init request & requestUrl
        request = (HttpRequestBase) params[0];
        requestUrl = request.getURI().toString();
        if (callback != null) {
            callback.setRequestUrl(requestUrl);
        }

        this.publishProgress(UPDATE_START);

        lastUpdateTime = SystemClock.uptimeMillis();

        ResponseInfo<T> responseInfo = sendRequest(request);
        if (responseInfo != null) {
            //?HttpClient?-1state     
            //SUCCESSBUG  
            if (isDownloadingFile) {
                responseInfo = checkoutFileLength(responseInfo);
            }
            if (responseInfo != null) {
                this.publishProgress(UPDATE_SUCCESS, responseInfo);
            } else {
                HttpException xException = new HttpException(8888, "inputstream errorcode -1");
                this.publishProgress(UPDATE_FAILURE, xException, xException.getMessage());
            }
            return null;
        }
    } catch (HttpException e) {
        this.publishProgress(UPDATE_FAILURE, e, e.getMessage());
    }

    return null;
}

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

/**
 * Execute a file download.//from   w w  w . j a  v  a  2s.  co m
 * 
 * @param fileId
 *            The file_id of the file to be downloaded
 * @param destinationFile
 *            A java.io.File resource to which the downloaded file will be written. Ensure that this points to a valid file-path that can be written to.
 * @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 File destinationFile, final Long versionId)
        throws IOException {

    final DefaultResponseParser handler = new DefaultResponseParser();

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

    // 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();
    HttpGet httpGet;
    try {
        httpGet = new HttpGet(new URI(builder.build().toString()));
    } catch (URISyntaxException e) {
        throw new IOException("Invalid Download URL");
    }
    HttpResponse httpResponse = httpclient.execute(httpGet);
    InputStream is = httpResponse.getEntity().getContent();
    int responseCode = httpResponse.getStatusLine().getStatusCode();

    if (responseCode == HttpURLConnection.HTTP_OK) {
        final FileOutputStream fos = new FileOutputStream(destinationFile);
        final byte[] buffer = new byte[DOWNLOAD_BUFFER_SIZE];
        int bufferLength = 0;
        mBytesTransferred = 0;
        long lastOnProgressPost = 0;
        while ((bufferLength = is.read(buffer)) > 0 && !Thread.currentThread().isInterrupted()) {
            fos.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);
        fos.close();
        handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_OK);

        // If download thread was interrupted, set to STATUS_DOWNLOAD_CANCELED
        if (Thread.currentThread().isInterrupted()) {
            handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_CANCELLED);
        }
        // Even if download completed, Box API may have put an error message
        // in the file itself. Refer to
        // http://developers.box.net/w/page/12923951/ApiFunction_Upload-and-Download
        else if (destinationFile.length() < FILE_ERROR_SIZE) {
            final byte[] buff = new byte[(int) destinationFile.length()];
            final FileInputStream fis = new FileInputStream(destinationFile);
            fis.read(buffer);
            final String str = new String(buff).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);
            }
        }
    } else if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
        handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_PERMISSIONS_ERROR);
    } else {
        handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_FAIL);
    }

    is.close();

    return handler;
}