Example usage for android.os Process THREAD_PRIORITY_BACKGROUND

List of usage examples for android.os Process THREAD_PRIORITY_BACKGROUND

Introduction

In this page you can find the example usage for android.os Process THREAD_PRIORITY_BACKGROUND.

Prototype

int THREAD_PRIORITY_BACKGROUND

To view the source code for android.os Process THREAD_PRIORITY_BACKGROUND.

Click Source Link

Document

Standard priority background threads.

Usage

From source file:biz.varkon.shelvesom.provider.comics.ComicsUpdater.java

public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    final ImageUtilities.ExpiringBitmap expiring = new ImageUtilities.ExpiringBitmap();

    while (!mStopped) {
        try {/*from ww  w.  ja va2 s .c om*/
            final String comicId = mQueue.take();

            final Long lastCheck = sLastChecks.get(comicId);
            if (lastCheck != null && (lastCheck + ONE_DAY) >= System.currentTimeMillis()) {
                continue;
            }
            sLastChecks.put(comicId, System.currentTimeMillis());

            final ComicsStore.Comic comic = ComicsManager.findComic(mResolver, comicId, null);

            if (comic == null)
                continue;

            final String imgURL = Preferences.getImageURLForUpdater(comic);

            if (comic.getLastModified() == null || imgURL == null) {
                continue;
            }

            if (comicCoverUpdated(comic, expiring) && expiring.lastModified != null) {
                ImageUtilities.deleteCachedCover(comicId);

                final Bitmap bitmap = Preferences.getBitmapForManager(comic);

                ImportUtilities.addCoverToCache(comic.getInternalId(), bitmap);

                if (bitmap != null)
                    bitmap.recycle();

                mValues.put(BaseItem.LAST_MODIFIED, expiring.lastModified.getTimeInMillis());
                mArguments[0] = comicId;
                mResolver.update(ComicsStore.Comic.CONTENT_URI, mValues, mSelection, mArguments);
            }

            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // Ignore
        }
    }
}

From source file:biz.varkon.shelvesom.provider.videogames.VideoGamesUpdater.java

public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    final ImageUtilities.ExpiringBitmap expiring = new ImageUtilities.ExpiringBitmap();

    while (!mStopped) {
        try {/*ww w  . j a  v a2  s  .  co  m*/
            final String videogameId = mQueue.take();

            final Long lastCheck = sLastChecks.get(videogameId);
            if (lastCheck != null && (lastCheck + ONE_DAY) >= System.currentTimeMillis()) {
                continue;
            }
            sLastChecks.put(videogameId, System.currentTimeMillis());

            final VideoGamesStore.VideoGame videogame = VideoGamesManager.findVideoGame(mResolver, videogameId,
                    null);

            if (videogame == null)
                continue;

            final String imgURL = Preferences.getImageURLForUpdater(videogame);

            if (videogame.getLastModified() == null || imgURL == null) {
                continue;
            }

            if (videogameCoverUpdated(videogame, expiring) && expiring.lastModified != null) {
                ImageUtilities.deleteCachedCover(videogameId);

                final Bitmap bitmap = Preferences.getBitmapForManager(videogame);

                ImportUtilities.addCoverToCache(videogame.getInternalId(), bitmap);

                if (bitmap != null)
                    bitmap.recycle();

                mValues.put(BaseItem.LAST_MODIFIED, expiring.lastModified.getTimeInMillis());
                mArguments[0] = videogameId;
                mResolver.update(VideoGamesStore.VideoGame.CONTENT_URI, mValues, mSelection, mArguments);
            }

            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // Ignore
        }
    }
}

From source file:biz.varkon.shelvesom.provider.boardgames.BoardGamesUpdater.java

public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    final ImageUtilities.ExpiringBitmap expiring = new ImageUtilities.ExpiringBitmap();

    while (!mStopped) {
        try {//  www . j a va  2 s  .  co m
            final String boardgameId = mQueue.take();

            final Long lastCheck = sLastChecks.get(boardgameId);
            if (lastCheck != null && (lastCheck + ONE_DAY) >= System.currentTimeMillis()) {
                continue;
            }
            sLastChecks.put(boardgameId, System.currentTimeMillis());

            final BoardGamesStore.BoardGame boardgame = BoardGamesManager.findBoardGame(mResolver, boardgameId,
                    null);

            if (boardgame == null)
                continue;

            final String imgURL = Preferences.getImageURLForUpdater(boardgame);

            if (boardgame.getLastModified() == null || imgURL == null) {
                continue;
            }

            if (boardgameCoverUpdated(boardgame, expiring) && expiring.lastModified != null) {
                ImageUtilities.deleteCachedCover(boardgameId);

                final Bitmap bitmap = Preferences.getBitmapForManager(boardgame);

                ImportUtilities.addCoverToCache(boardgame.getInternalId(), bitmap);

                if (bitmap != null)
                    bitmap.recycle();

                mValues.put(BaseItem.LAST_MODIFIED, expiring.lastModified.getTimeInMillis());
                mArguments[0] = boardgameId;
                mResolver.update(BoardGamesStore.BoardGame.CONTENT_URI, mValues, mSelection, mArguments);
            }

            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // Ignore
        }
    }
}

From source file:com.androidrocks.bex.provider.BooksUpdater.java

public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    final ImageUtilities.ExpiringBitmap expiring = new ImageUtilities.ExpiringBitmap();

    while (!mStopped) {
        try {//ww w. j av  a2  s.com
            final String bookId = mQueue.take();

            final Long lastCheck = sLastChecks.get(bookId);
            if (lastCheck != null && (lastCheck + ONE_DAY) >= System.currentTimeMillis()) {
                continue;
            }
            sLastChecks.put(bookId, System.currentTimeMillis());

            final BooksStore.Book book = BooksManager.findBook(mResolver, bookId);
            if (book.getLastModified() == null || book.getImageUrl(BooksStore.ImageSize.TINY) == null) {
                continue;
            }

            if (bookCoverUpdated(book, expiring) && expiring.lastModified != null) {
                ImageUtilities.deleteCachedCover(bookId);
                final Bitmap bitmap = book.loadCover(BooksStore.ImageSize.TINY);
                ImportUtilities.addBookCoverToCache(book, bitmap);

                mValues.put(BooksStore.Book.LAST_MODIFIED, expiring.lastModified.getTimeInMillis());
                mArguments[0] = bookId;
                mResolver.update(BooksStore.Book.CONTENT_URI, mValues, mSelection, mArguments);
            }

            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // Ignore
        }
    }
}

From source file:com.mobilesolutionworks.android.http.WorksHttpFutureTask.java

/**
 * Execute specified works http request in parallel.
 *
 * @param request works http request//www. jav a  2s  .c  om
 * @param handler android handler
 * @param exec    executor so it can be run in serial or other controlled manner
 */
public void execute(WorksHttpRequest request, Handler handler, Executor exec) {
    mWorker = new WorkerRunnable<WorksHttpRequest, Result>() {
        @Override
        public Result call() throws Exception {
            Thread.currentThread()
                    .setUncaughtExceptionHandler(new UncaughtExceptionHandler(mHandler, mParams[0]));

            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            WorksHttpResponse<Result> response = WorksHttpClient.executeOperation(mContext, mParams[0],
                    WorksHttpFutureTask.this);

            return postResult(mHandler, response);
        }
    };

    mFuture = new FutureTask<Result>(mWorker);

    mWorker.mHandler = handler;
    mWorker.mParams = new WorksHttpRequest[] { request };
    exec.execute(mFuture);
}

From source file:com.aimfire.gallery.service.MovieProcessor.java

@Override
protected void onHandleIntent(Intent intent) {
    /*//from   w w  w.  j  a  va2s  .  c  o m
     * Obtain the FirebaseAnalytics instance.
     */
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

    boolean[] result = new boolean[] { false, false };
    String previewPath = null;
    String thumbPath = null;
    String configPath = null;
    String convertFilePath = null;

    String exportL = MainConsts.MEDIA_3D_RAW_PATH + "L.png";
    String exportR = MainConsts.MEDIA_3D_RAW_PATH + "R.png";

    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    Bundle extras = intent.getExtras();
    if (extras == null) {
        if (BuildConfig.DEBUG)
            Log.e(TAG, "onHandleIntent: error, wrong parameter");
        FirebaseCrash.report(new Exception("onHandleIntent: error, wrong parameter"));
        return;
    }

    String filePathL = extras.getString("lname");
    String filePathR = extras.getString("rname");
    String cvrNameNoExt = MediaScanner.getProcessedCvrName((new File(filePathL)).getName());

    if (BuildConfig.DEBUG)
        Log.d(TAG, "onHandleIntent:left file=" + filePathL + ", right file=" + filePathR);

    String creatorName = extras.getString("creator");
    String creatorPhotoUrl = extras.getString("photo");

    float scale = extras.getFloat(MainConsts.EXTRA_SCALE);

    /*
     * if left/right videos were taken using front facing camera,
     * they need to be swapped when generating sbs 
     */
    int facing = extras.getInt(MainConsts.EXTRA_FACING);
    boolean isFrontCamera = (facing == Camera.CameraInfo.CAMERA_FACING_FRONT) ? true : false;

    MediaMetadataRetriever retriever = new MediaMetadataRetriever();

    Bitmap bitmapL = null;
    Bitmap bitmapR = null;

    long frameTime = FIRST_KEYFRAME_TIME_US;
    if (BuildConfig.DEBUG)
        Log.d(TAG, "extract frame from left at " + frameTime / 1000 + "ms");

    try {
        long startUs = SystemClock.elapsedRealtimeNanos() / 1000;

        FileInputStream inputStreamL = new FileInputStream(filePathL);
        retriever.setDataSource(inputStreamL.getFD());
        inputStreamL.close();

        bitmapL = retriever.getFrameAtTime(frameTime, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);

        FileInputStream inputStreamR = new FileInputStream(filePathR);
        retriever.setDataSource(inputStreamR.getFD());
        inputStreamR.close();

        bitmapR = retriever.getFrameAtTime(frameTime, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);

        retriever.release();

        long stopUs = SystemClock.elapsedRealtimeNanos() / 1000;
        if (BuildConfig.DEBUG)
            Log.d(TAG, "retrieving preview frames took " + (stopUs - startUs) / 1000 + "ms");

        if ((bitmapL != null) && (bitmapR != null)) {
            saveFrame(bitmapL, exportL);
            saveFrame(bitmapR, exportR);
        } else {
            reportError(MediaScanner.getProcessedCvrPath((new File(filePathL)).getName()),
                    ERROR_EXTRACT_SYNC_FRAME_ERROR);
            return;
        }

        previewPath = MainConsts.MEDIA_3D_THUMB_PATH + cvrNameNoExt + ".jpeg";

        result = p.getInstance().f1(exportL, exportR, previewPath, scale, isFrontCamera);
    } catch (Exception ex) {
        retriever.release();
        reportError(MediaScanner.getProcessedCvrPath((new File(filePathL)).getName()),
                ERROR_EXTRACT_SYNC_FRAME_EXCEPTION);
        return;
    }

    if (!result[0]) {
        reportError(MediaScanner.getProcessedCvrPath((new File(filePathL)).getName()),
                ERROR_EXTRACT_SIMILARITY_MATRIX);

        File leftFrom = (new File(filePathL));
        File rightFrom = (new File(filePathR));
        File leftExportFrom = (new File(exportL));
        File rightExportFrom = (new File(exportR));

        if (!BuildConfig.DEBUG) {
            leftFrom.delete();
            rightFrom.delete();

            leftExportFrom.delete();
            rightExportFrom.delete();
        } else {
            File leftTo = new File(MainConsts.MEDIA_3D_DEBUG_PATH + leftFrom.getName());
            File rightTo = new File(MainConsts.MEDIA_3D_DEBUG_PATH + rightFrom.getName());

            leftFrom.renameTo(leftTo);
            rightFrom.renameTo(rightTo);

            File leftExportTo = new File(MainConsts.MEDIA_3D_DEBUG_PATH + leftExportFrom.getName());
            File rightExportTo = new File(MainConsts.MEDIA_3D_DEBUG_PATH + rightExportFrom.getName());

            leftExportFrom.renameTo(leftExportTo);
            rightExportFrom.renameTo(rightExportTo);
        }
    } else {
        double[] similarityMat = p.getInstance().g();

        String configData = similarityMat[0] + " " + similarityMat[1] + " " + similarityMat[2] + " "
                + similarityMat[3] + " " + similarityMat[4] + " " + similarityMat[5];

        if (result[1]) {
            convertFilePath = filePathR;
        } else {
            convertFilePath = filePathL;
        }

        configPath = createConfigFile(convertFilePath, configData);

        /*
         * save the thumbnail
         */
        if (bitmapL != null) {
            thumbPath = MainConsts.MEDIA_3D_THUMB_PATH + cvrNameNoExt + ".jpg";
            saveThumbnail(bitmapL, thumbPath);

            MediaScanner.insertExifInfo(thumbPath, "name=" + creatorName + "photourl=" + creatorPhotoUrl);
        }

        createZipFile(filePathL, filePathR, configPath, thumbPath, previewPath);

        /*
         * let CamcorderActivity know we are done.
         */
        reportResult(MediaScanner.getProcessedCvrPath((new File(filePathL)).getName()));
    }

    /*
     * paranoia
     */
    if (bitmapL != null) {
        bitmapL.recycle();
    }
    if (bitmapR != null) {
        bitmapR.recycle();
    }

    (new File(exportL)).delete();
    (new File(exportR)).delete();
}

From source file:sample.multithreading.NetworkDownloadService.java

@Override
protected void onHandleIntent(Intent paramIntent) {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    String str = paramIntent.getDataString();
    URL localURL;/*from   ww w. ja  v  a  2s. co  m*/
    try {
        localURL = new URL(str);
        URLConnection localURLConnection = localURL.openConnection();
        if ((localURLConnection instanceof HttpURLConnection)) {
            broadcastIntentWithState(STATE_ACTION_STARTED);
            HttpURLConnection localHttpURLConnection = (HttpURLConnection) localURLConnection;
            localHttpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
            broadcastIntentWithState(STATE_ACTION_CONNECTING);
            localHttpURLConnection.getResponseCode();
            broadcastIntentWithState(STATE_ACTION_PARSING);
            PicasaPullParser localPicasaPullParser = new PicasaPullParser();
            localPicasaPullParser.parseXml(localURLConnection.getInputStream(), this);
            broadcastIntentWithState(STATE_ACTION_WRITING);
            Vector<ContentValues> cvv = localPicasaPullParser.getImages();
            int size = cvv.size();
            ContentValues[] cvArray = new ContentValues[size];
            cvArray = cvv.toArray(cvArray);
            getContentResolver().bulkInsert(PicasaContentDB.getUriByType(this, PicasaContentDB.METADATA_QUERY),
                    cvArray);
            broadcastIntentWithState(STATE_ACTION_COMPLETE);
        }
    } catch (MalformedURLException localMalformedURLException) {
        localMalformedURLException.printStackTrace();
    } catch (IOException localIOException) {
        localIOException.printStackTrace();
    } catch (XmlPullParserException localXmlPullParserException) {
        localXmlPullParserException.printStackTrace();
    }
    Log.d(LOG_TAG, "onHandleIntent Complete");
}

From source file:de.schildbach.wallet.ui.AlertDialogsFragment.java

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    backgroundThread = new HandlerThread("backgroundThread", Process.THREAD_PRIORITY_BACKGROUND);
    backgroundThread.start();/* ww w  .j a  v a 2 s .c o  m*/
    backgroundHandler = new Handler(backgroundThread.getLooper());

    final PackageInfo packageInfo = application.packageInfo();
    final int versionNameSplit = packageInfo.versionName.indexOf('-');
    final HttpUrl.Builder url = HttpUrl
            .parse(Constants.VERSION_URL
                    + (versionNameSplit >= 0 ? packageInfo.versionName.substring(versionNameSplit) : ""))
            .newBuilder();
    url.addEncodedQueryParameter("package", packageInfo.packageName);
    url.addEncodedQueryParameter("installer",
            Strings.nullToEmpty(packageManager.getInstallerPackageName(packageInfo.packageName)));
    url.addQueryParameter("current", Integer.toString(packageInfo.versionCode));
    versionUrl = url.build();
}

From source file:com.android.callstat.common.net.ConnectionThread.java

/**
 * Loop until app shutdown.//from   w ww .  j  a va  2 s.  co m
 */
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    // these are used to get performance data. When it is not in the timing,
    // mCurrentThreadTime is 0. When it starts timing, mCurrentThreadTime is
    // first set to -1, it will be set to the current thread time when the
    // next request starts.
    mCurrentThreadTime = 0;
    mTotalThreadTime = 0;

    MyHttpClient client = null;
    client = createHttpClient(mContext);

    while (mRunning) {
        if (mCurrentThreadTime == -1) {
            mCurrentThreadTime = SystemClock.currentThreadTimeMillis();
        }

        Request request;

        // mCancaled = false;
        /* Get a request to process */
        request = mRequestFeeder.getRequest();

        /* wait for work */
        if (request == null) {
            synchronized (mRequestFeeder) {
                if (DebugFlags.CONNECTION_THREAD)
                    HttpLog.v("ConnectionThread: Waiting for work");
                try {
                    mRequestFeeder.wait();
                } catch (InterruptedException e) {
                }
                if (mCurrentThreadTime != 0) {
                    mCurrentThreadTime = SystemClock.currentThreadTimeMillis();
                }
            }
        } else {
            if (DebugFlags.CONNECTION_THREAD) {
                // HttpLog.v("ConnectionThread: new request " +
                // request.mHost + " " + request );
            }
            try {
                httpConnection(mContext, false, client, null, 0, request);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    if (client != null) {
        client.close();
    }
}

From source file:net.impjq.providers.downloads.DownloadThread.java

/**
 * Executes the download in a separate thread
 *///from w w  w .j  a v  a  2 s  .  c  o m
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    int finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR;
    boolean countRetry = false;
    int retryAfter = 0;
    int redirectCount = mInfo.mRedirectCount;
    String newUri = null;
    boolean gotData = false;
    String filename = null;
    String mimeType = sanitizeMimeType(mInfo.mMimeType);
    FileOutputStream stream = null;
    AndroidHttpClient client = null;
    PowerManager.WakeLock wakeLock = null;
    Uri contentUri = Uri.parse(Downloads.Impl.CONTENT_URI + "/" + mInfo.mId);

    try {
        boolean continuingDownload = false;
        String headerAcceptRanges = null;
        String headerContentDisposition = null;
        String headerContentLength = null;
        String headerContentLocation = null;
        String headerETag = null;
        String headerTransferEncoding = null;

        byte data[] = new byte[Constants.BUFFER_SIZE];

        int bytesSoFar = 0;

        PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
        wakeLock.acquire();

        filename = mInfo.mFileName;
        if (filename != null) {
            if (!Helpers.isFilenameValid(filename)) {
                finalStatus = Downloads.Impl.STATUS_FILE_ERROR;
                notifyDownloadCompleted(finalStatus, false, 0, 0, false, filename, null, mInfo.mMimeType);
                return;
            }
            // We're resuming a download that got interrupted
            File f = new File(filename);
            if (f.exists()) {
                long fileLength = f.length();
                if (fileLength == 0) {
                    // The download hadn't actually started, we can restart from scratch
                    f.delete();
                    filename = null;
                } else if (mInfo.mETag == null && !mInfo.mNoIntegrity) {
                    // Tough luck, that's not a resumable download
                    if (Config.LOGD) {
                        Log.d(Constants.TAG, "can't resume interrupted non-resumable download");
                    }
                    f.delete();
                    finalStatus = Downloads.Impl.STATUS_PRECONDITION_FAILED;
                    notifyDownloadCompleted(finalStatus, false, 0, 0, false, filename, null, mInfo.mMimeType);
                    return;
                } else {
                    // All right, we'll be able to resume this download
                    stream = new FileOutputStream(filename, true);
                    bytesSoFar = (int) fileLength;
                    if (mInfo.mTotalBytes != -1) {
                        headerContentLength = Integer.toString(mInfo.mTotalBytes);
                    }
                    headerETag = mInfo.mETag;
                    continuingDownload = true;
                }
            }
        }

        int bytesNotified = bytesSoFar;
        // starting with MIN_VALUE means that the first write will commit
        //     progress to the database
        long timeLastNotification = 0;

        client = AndroidHttpClient.newInstance(userAgent(), mContext);

        if (stream != null && mInfo.mDestination == Downloads.Impl.DESTINATION_EXTERNAL) {
            try {
                stream.close();
                stream = null;
            } catch (IOException ex) {
                if (Constants.LOGV) {
                    Log.v(Constants.TAG, "exception when closing the file before download : " + ex);
                }
                // nothing can really be done if the file can't be closed
            }
        }

        /*
         * This loop is run once for every individual HTTP request that gets sent.
         * The very first HTTP request is a "virgin" request, while every subsequent
         * request is done with the original ETag and a byte-range.
         */
        http_request_loop: while (true) {
            // Set or unset proxy, which may have changed since last GET request.
            // setDefaultProxy() supports null as proxy parameter.
            //Comment it,pjq,20110220,start
            //ConnRouteParams.setDefaultProxy(client.getParams(),
            //         Proxy.getPreferredHttpHost(mContext, mInfo.mUri));
            // Prepares the request and fires it.
            HttpGet request = new HttpGet(mInfo.mUri);

            if (Constants.LOGV) {
                Log.v(Constants.TAG, "initiating download for " + mInfo.mUri);
            }

            if (mInfo.mCookies != null) {
                request.addHeader("Cookie", mInfo.mCookies);
            }
            if (mInfo.mReferer != null) {
                request.addHeader("Referer", mInfo.mReferer);
            }
            if (continuingDownload) {
                if (headerETag != null) {
                    request.addHeader("If-Match", headerETag);
                }
                request.addHeader("Range", "bytes=" + bytesSoFar + "-");
            }

            HttpResponse response;
            try {
                response = client.execute(request);
            } catch (IllegalArgumentException ex) {
                if (Constants.LOGV) {
                    Log.d(Constants.TAG,
                            "Arg exception trying to execute request for " + mInfo.mUri + " : " + ex);
                } else if (Config.LOGD) {
                    Log.d(Constants.TAG,
                            "Arg exception trying to execute request for " + mInfo.mId + " : " + ex);
                }
                finalStatus = Downloads.Impl.STATUS_BAD_REQUEST;
                request.abort();
                break http_request_loop;
            } catch (IOException ex) {
                ex.printStackTrace();
                if (Constants.LOGX) {
                    if (Helpers.isNetworkAvailable(mContext)) {
                        Log.i(Constants.TAG, "Execute Failed " + mInfo.mId + ", Net Up");
                    } else {
                        Log.i(Constants.TAG, "Execute Failed " + mInfo.mId + ", Net Down");
                    }
                }
                if (!Helpers.isNetworkAvailable(mContext)) {
                    finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED;
                } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) {
                    finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED;
                    countRetry = true;
                } else {
                    if (Constants.LOGV) {
                        Log.d(Constants.TAG,
                                "IOException trying to execute request for " + mInfo.mUri + " : " + ex);
                    } else if (Config.LOGD) {
                        Log.d(Constants.TAG,
                                "IOException trying to execute request for " + mInfo.mId + " : " + ex);
                    }
                    finalStatus = Downloads.Impl.STATUS_HTTP_DATA_ERROR;
                }
                request.abort();
                break http_request_loop;
            }

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 503 && mInfo.mNumFailed < Constants.MAX_RETRIES) {
                if (Constants.LOGVV) {
                    Log.v(Constants.TAG, "got HTTP response code 503");
                }
                finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED;
                countRetry = true;
                Header header = response.getFirstHeader("Retry-After");
                if (header != null) {
                    try {
                        if (Constants.LOGVV) {
                            Log.v(Constants.TAG, "Retry-After :" + header.getValue());
                        }
                        retryAfter = Integer.parseInt(header.getValue());
                        if (retryAfter < 0) {
                            retryAfter = 0;
                        } else {
                            if (retryAfter < Constants.MIN_RETRY_AFTER) {
                                retryAfter = Constants.MIN_RETRY_AFTER;
                            } else if (retryAfter > Constants.MAX_RETRY_AFTER) {
                                retryAfter = Constants.MAX_RETRY_AFTER;
                            }
                            retryAfter += Helpers.sRandom.nextInt(Constants.MIN_RETRY_AFTER + 1);
                            retryAfter *= 1000;
                        }
                    } catch (NumberFormatException ex) {
                        // ignored - retryAfter stays 0 in this case.
                    }
                }
                request.abort();
                break http_request_loop;
            }
            if (statusCode == 301 || statusCode == 302 || statusCode == 303 || statusCode == 307) {
                if (Constants.LOGVV) {
                    Log.v(Constants.TAG, "got HTTP redirect " + statusCode);
                }
                if (redirectCount >= Constants.MAX_REDIRECTS) {
                    if (Constants.LOGV) {
                        Log.d(Constants.TAG,
                                "too many redirects for download " + mInfo.mId + " at " + mInfo.mUri);
                    } else if (Config.LOGD) {
                        Log.d(Constants.TAG, "too many redirects for download " + mInfo.mId);
                    }
                    finalStatus = Downloads.Impl.STATUS_TOO_MANY_REDIRECTS;
                    request.abort();
                    break http_request_loop;
                }
                Header header = response.getFirstHeader("Location");
                if (header != null) {
                    if (Constants.LOGVV) {
                        Log.v(Constants.TAG, "Location :" + header.getValue());
                    }
                    try {
                        newUri = new URI(mInfo.mUri).resolve(new URI(header.getValue())).toString();
                    } catch (URISyntaxException ex) {
                        if (Constants.LOGV) {
                            Log.d(Constants.TAG, "Couldn't resolve redirect URI " + header.getValue() + " for "
                                    + mInfo.mUri);
                        } else if (Config.LOGD) {
                            Log.d(Constants.TAG, "Couldn't resolve redirect URI for download " + mInfo.mId);
                        }
                        finalStatus = Downloads.Impl.STATUS_BAD_REQUEST;
                        request.abort();
                        break http_request_loop;
                    }
                    ++redirectCount;
                    finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED;
                    request.abort();
                    break http_request_loop;
                }
            }
            if ((!continuingDownload && statusCode != Downloads.Impl.STATUS_SUCCESS)
                    || (continuingDownload && statusCode != 206)) {
                if (Constants.LOGV) {
                    Log.d(Constants.TAG, "http error " + statusCode + " for " + mInfo.mUri);
                } else if (Config.LOGD) {
                    Log.d(Constants.TAG, "http error " + statusCode + " for download " + mInfo.mId);
                }
                if (Downloads.Impl.isStatusError(statusCode)) {
                    finalStatus = statusCode;
                } else if (statusCode >= 300 && statusCode < 400) {
                    finalStatus = Downloads.Impl.STATUS_UNHANDLED_REDIRECT;
                } else if (continuingDownload && statusCode == Downloads.Impl.STATUS_SUCCESS) {
                    finalStatus = Downloads.Impl.STATUS_PRECONDITION_FAILED;
                } else {
                    finalStatus = Downloads.Impl.STATUS_UNHANDLED_HTTP_CODE;
                }
                request.abort();
                break http_request_loop;
            } else {
                // Handles the response, saves the file
                if (Constants.LOGV) {
                    Log.v(Constants.TAG, "received response for " + mInfo.mUri);
                }

                if (!continuingDownload) {
                    Header header = response.getFirstHeader("Accept-Ranges");
                    if (header != null) {
                        headerAcceptRanges = header.getValue();
                    }
                    header = response.getFirstHeader("Content-Disposition");
                    if (header != null) {
                        headerContentDisposition = header.getValue();
                    }
                    header = response.getFirstHeader("Content-Location");
                    if (header != null) {
                        headerContentLocation = header.getValue();
                    }
                    if (mimeType == null) {
                        header = response.getFirstHeader("Content-Type");
                        if (header != null) {
                            mimeType = sanitizeMimeType(header.getValue());
                        }
                    }
                    header = response.getFirstHeader("ETag");
                    if (header != null) {
                        headerETag = header.getValue();
                    }
                    header = response.getFirstHeader("Transfer-Encoding");
                    if (header != null) {
                        headerTransferEncoding = header.getValue();
                    }
                    if (headerTransferEncoding == null) {
                        header = response.getFirstHeader("Content-Length");
                        if (header != null) {
                            headerContentLength = header.getValue();
                        }
                    } else {
                        // Ignore content-length with transfer-encoding - 2616 4.4 3
                        if (Constants.LOGVV) {
                            Log.v(Constants.TAG, "ignoring content-length because of xfer-encoding");
                        }
                    }
                    if (Constants.LOGVV) {
                        Log.v(Constants.TAG, "Accept-Ranges: " + headerAcceptRanges);
                        Log.v(Constants.TAG, "Content-Disposition: " + headerContentDisposition);
                        Log.v(Constants.TAG, "Content-Length: " + headerContentLength);
                        Log.v(Constants.TAG, "Content-Location: " + headerContentLocation);
                        Log.v(Constants.TAG, "Content-Type: " + mimeType);
                        Log.v(Constants.TAG, "ETag: " + headerETag);
                        Log.v(Constants.TAG, "Transfer-Encoding: " + headerTransferEncoding);
                    }

                    if (!mInfo.mNoIntegrity && headerContentLength == null && (headerTransferEncoding == null
                            || !headerTransferEncoding.equalsIgnoreCase("chunked"))) {
                        if (Config.LOGD) {
                            Log.d(Constants.TAG, "can't know size of download, giving up");
                        }
                        finalStatus = Downloads.Impl.STATUS_LENGTH_REQUIRED;
                        request.abort();
                        break http_request_loop;
                    }

                    DownloadFileInfo fileInfo = Helpers.generateSaveFile(mContext, mInfo.mUri, mInfo.mHint,
                            headerContentDisposition, headerContentLocation, mimeType, mInfo.mDestination,
                            (headerContentLength != null) ? Integer.parseInt(headerContentLength) : 0);
                    if (fileInfo.mFileName == null) {
                        finalStatus = fileInfo.mStatus;
                        request.abort();
                        break http_request_loop;
                    }
                    filename = fileInfo.mFileName;
                    stream = fileInfo.mStream;
                    if (Constants.LOGV) {
                        Log.v(Constants.TAG, "writing " + mInfo.mUri + " to " + filename);
                    }

                    ContentValues values = new ContentValues();
                    values.put(Downloads.Impl._DATA, filename);
                    if (headerETag != null) {
                        values.put(Constants.ETAG, headerETag);
                    }
                    if (mimeType != null) {
                        values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimeType);
                    }
                    int contentLength = -1;
                    if (headerContentLength != null) {
                        contentLength = Integer.parseInt(headerContentLength);
                    }
                    values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
                    mContext.getContentResolver().update(contentUri, values, null, null);
                }

                InputStream entityStream;
                try {
                    entityStream = response.getEntity().getContent();
                } catch (IOException ex) {
                    if (Constants.LOGX) {
                        if (Helpers.isNetworkAvailable(mContext)) {
                            Log.i(Constants.TAG, "Get Failed " + mInfo.mId + ", Net Up");
                        } else {
                            Log.i(Constants.TAG, "Get Failed " + mInfo.mId + ", Net Down");
                        }
                    }
                    if (!Helpers.isNetworkAvailable(mContext)) {
                        finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED;
                    } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) {
                        finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED;
                        countRetry = true;
                    } else {
                        if (Constants.LOGV) {
                            Log.d(Constants.TAG, "IOException getting entity for " + mInfo.mUri + " : " + ex);
                        } else if (Config.LOGD) {
                            Log.d(Constants.TAG,
                                    "IOException getting entity for download " + mInfo.mId + " : " + ex);
                        }
                        finalStatus = Downloads.Impl.STATUS_HTTP_DATA_ERROR;
                    }
                    request.abort();
                    break http_request_loop;
                }
                for (;;) {
                    int bytesRead;
                    try {
                        bytesRead = entityStream.read(data);
                    } catch (IOException ex) {
                        if (Constants.LOGX) {
                            if (Helpers.isNetworkAvailable(mContext)) {
                                Log.i(Constants.TAG, "Read Failed " + mInfo.mId + ", Net Up");
                            } else {
                                Log.i(Constants.TAG, "Read Failed " + mInfo.mId + ", Net Down");
                            }
                        }
                        ContentValues values = new ContentValues();
                        values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, bytesSoFar);
                        mContext.getContentResolver().update(contentUri, values, null, null);
                        if (!mInfo.mNoIntegrity && headerETag == null) {
                            if (Constants.LOGV) {
                                Log.v(Constants.TAG, "download IOException for " + mInfo.mUri + " : " + ex);
                            } else if (Config.LOGD) {
                                Log.d(Constants.TAG,
                                        "download IOException for download " + mInfo.mId + " : " + ex);
                            }
                            if (Config.LOGD) {
                                Log.d(Constants.TAG, "can't resume interrupted download with no ETag");
                            }
                            finalStatus = Downloads.Impl.STATUS_PRECONDITION_FAILED;
                        } else if (!Helpers.isNetworkAvailable(mContext)) {
                            finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED;
                        } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) {
                            finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED;
                            countRetry = true;
                        } else {
                            if (Constants.LOGV) {
                                Log.v(Constants.TAG, "download IOException for " + mInfo.mUri + " : " + ex);
                            } else if (Config.LOGD) {
                                Log.d(Constants.TAG,
                                        "download IOException for download " + mInfo.mId + " : " + ex);
                            }
                            finalStatus = Downloads.Impl.STATUS_HTTP_DATA_ERROR;
                        }
                        request.abort();
                        break http_request_loop;
                    }
                    if (bytesRead == -1) { // success
                        ContentValues values = new ContentValues();
                        values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, bytesSoFar);
                        if (headerContentLength == null) {
                            values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, bytesSoFar);
                        }
                        mContext.getContentResolver().update(contentUri, values, null, null);
                        if ((headerContentLength != null)
                                && (bytesSoFar != Integer.parseInt(headerContentLength))) {
                            if (!mInfo.mNoIntegrity && headerETag == null) {
                                if (Constants.LOGV) {
                                    Log.d(Constants.TAG, "mismatched content length " + mInfo.mUri);
                                } else if (Config.LOGD) {
                                    Log.d(Constants.TAG, "mismatched content length for " + mInfo.mId);
                                }
                                finalStatus = Downloads.Impl.STATUS_LENGTH_REQUIRED;
                            } else if (!Helpers.isNetworkAvailable(mContext)) {
                                finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED;
                            } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) {
                                finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED;
                                countRetry = true;
                            } else {
                                if (Constants.LOGV) {
                                    Log.v(Constants.TAG, "closed socket for " + mInfo.mUri);
                                } else if (Config.LOGD) {
                                    Log.d(Constants.TAG, "closed socket for download " + mInfo.mId);
                                }
                                finalStatus = Downloads.Impl.STATUS_HTTP_DATA_ERROR;
                            }
                            break http_request_loop;
                        }
                        break;
                    }
                    gotData = true;
                    for (;;) {
                        try {
                            if (stream == null) {
                                stream = new FileOutputStream(filename, true);
                            }
                            stream.write(data, 0, bytesRead);
                            if (mInfo.mDestination == Downloads.Impl.DESTINATION_EXTERNAL) {
                                try {
                                    stream.close();
                                    stream = null;
                                } catch (IOException ex) {
                                    if (Constants.LOGV) {
                                        Log.v(Constants.TAG,
                                                "exception when closing the file " + "during download : " + ex);
                                    }
                                    // nothing can really be done if the file can't be closed
                                }
                            }
                            break;
                        } catch (IOException ex) {
                            if (!Helpers.discardPurgeableFiles(mContext, Constants.BUFFER_SIZE)) {
                                finalStatus = Downloads.Impl.STATUS_FILE_ERROR;
                                break http_request_loop;
                            }
                        }
                    }
                    bytesSoFar += bytesRead;
                    long now = System.currentTimeMillis();
                    if (bytesSoFar - bytesNotified > Constants.MIN_PROGRESS_STEP
                            && now - timeLastNotification > Constants.MIN_PROGRESS_TIME) {
                        ContentValues values = new ContentValues();
                        values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, bytesSoFar);
                        mContext.getContentResolver().update(contentUri, values, null, null);
                        bytesNotified = bytesSoFar;
                        timeLastNotification = now;
                    }

                    if (Constants.LOGVV) {
                        Log.v(Constants.TAG, "downloaded " + bytesSoFar + " for " + mInfo.mUri);
                    }
                    synchronized (mInfo) {
                        if (mInfo.mControl == Downloads.Impl.CONTROL_PAUSED) {
                            if (Constants.LOGV) {
                                Log.v(Constants.TAG, "paused " + mInfo.mUri);
                            }
                            finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED;
                            request.abort();
                            break http_request_loop;
                        }
                    }
                    if (mInfo.mStatus == Downloads.Impl.STATUS_CANCELED) {
                        if (Constants.LOGV) {
                            Log.d(Constants.TAG, "canceled " + mInfo.mUri);
                        } else if (Config.LOGD) {
                            // Log.d(Constants.TAG, "canceled id " + mInfo.mId);
                        }
                        finalStatus = Downloads.Impl.STATUS_CANCELED;
                        break http_request_loop;
                    }
                }
                if (Constants.LOGV) {
                    Log.v(Constants.TAG, "download completed for " + mInfo.mUri);
                }
                finalStatus = Downloads.Impl.STATUS_SUCCESS;
            }
            break;
        }
    } catch (FileNotFoundException ex) {
        if (Config.LOGD) {
            Log.d(Constants.TAG, "FileNotFoundException for " + filename + " : " + ex);
        }
        finalStatus = Downloads.Impl.STATUS_FILE_ERROR;
        // falls through to the code that reports an error
    } catch (RuntimeException ex) { //sometimes the socket code throws unchecked exceptions
        if (Constants.LOGV) {
            Log.d(Constants.TAG, "Exception for " + mInfo.mUri, ex);
        } else if (Config.LOGD) {
            Log.d(Constants.TAG, "Exception for id " + mInfo.mId, ex);
        }
        finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR;
        // falls through to the code that reports an error
    } finally {
        mInfo.mHasActiveThread = false;
        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
        if (client != null) {
            client.close();
            client = null;
        }
        try {
            // close the file
            if (stream != null) {
                stream.close();
            }
        } catch (IOException ex) {
            if (Constants.LOGV) {
                Log.v(Constants.TAG, "exception when closing the file after download : " + ex);
            }
            // nothing can really be done if the file can't be closed
        }
        if (filename != null) {
            // if the download wasn't successful, delete the file
            if (Downloads.Impl.isStatusError(finalStatus)) {
                new File(filename).delete();
                filename = null;
            } else if (Downloads.Impl.isStatusSuccess(finalStatus)) {
                //Comment it,pjq,20110220,start
                // transfer the file to the DRM content provider 
                // File file = new File(filename);
                // Intent item =
                // DrmStore.addDrmFile(mContext.getContentResolver(), file,
                // null);
                // if (item == null) {
                // Log.w(Constants.TAG, "unable to add file " + filename +
                // " to DrmProvider");
                // finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR;
                // } else {
                // filename = item.getDataString();
                // mimeType = item.getType();
                // }
                //                    
                // file.delete();
            } else if (Downloads.Impl.isStatusSuccess(finalStatus)) {
                // make sure the file is readable
                //Comment it,pjq,20110220,start
                //FileUtils.setPermissions(filename, 0644, -1, -1);

                // Sync to storage after completion
                FileOutputStream downloadedFileStream = null;
                try {
                    downloadedFileStream = new FileOutputStream(filename, true);
                    downloadedFileStream.getFD().sync();
                } catch (FileNotFoundException ex) {
                    Log.w(Constants.TAG, "file " + filename + " not found: " + ex);
                } catch (SyncFailedException ex) {
                    Log.w(Constants.TAG, "file " + filename + " sync failed: " + ex);
                } catch (IOException ex) {
                    Log.w(Constants.TAG, "IOException trying to sync " + filename + ": " + ex);
                } catch (RuntimeException ex) {
                    Log.w(Constants.TAG, "exception while syncing file: ", ex);
                } finally {
                    if (downloadedFileStream != null) {
                        try {
                            downloadedFileStream.close();
                        } catch (IOException ex) {
                            Log.w(Constants.TAG, "IOException while closing synced file: ", ex);
                        } catch (RuntimeException ex) {
                            Log.w(Constants.TAG, "exception while closing file: ", ex);
                        }
                    }
                }
            }
        }
        notifyDownloadCompleted(finalStatus, countRetry, retryAfter, redirectCount, gotData, filename, newUri,
                mimeType);
    }
}