Example usage for android.os Process setThreadPriority

List of usage examples for android.os Process setThreadPriority

Introduction

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

Prototype

public static final native void setThreadPriority(int priority)
        throws IllegalArgumentException, SecurityException;

Source Link

Document

Set the priority of the calling thread, based on Linux priorities.

Usage

From source file:com.nextgis.maplibui.service.RebuildCacheService.java

protected void startNextTask() {
    if (mQueue.isEmpty()) {
        mCurrentTasks = 0;/*  w  w  w. j a  va2s  . c  o m*/
        mNotifyManager.cancel(NOTIFICATION_ID);
        mProgressIntent.putExtra(KEY_PROGRESS, 0);
        sendBroadcast(mProgressIntent);
        mLayer = null;
        stopSelf();
        return;
    }

    mIsCanceled = false;
    final IProgressor progressor = this;
    new Thread(new Runnable() {
        @Override
        public void run() {
            mLayer = (VectorLayer) MapBase.getInstance().getLayerById(mQueue.remove(0));
            mIsRunning = true;
            mCurrentTasks++;
            String notifyTitle = getString(R.string.rebuild_cache) + ": " + mCurrentTasks + "/" + mQueue.size()
                    + 1;

            mBuilder.setWhen(System.currentTimeMillis()).setContentTitle(notifyTitle).setTicker(notifyTitle);
            mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());

            Process.setThreadPriority(Constants.DEFAULT_DOWNLOAD_THREAD_PRIORITY);
            if (mLayer != null)
                mLayer.rebuildCache(progressor);

            mIsRunning = mRemoveCurrent = false;
            startNextTask();
        }
    }).start();

}

From source file:com.android.launcher2.AsyncTaskCallback.java

void syncThreadPriority() {
    Process.setThreadPriority(threadPriority);
}

From source file:tree.love.providers.downloads.DownloadThread.java

@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    try {/*from w w  w.  j a  v  a2  s .  co m*/
        runInternal();
    } finally {
        mNotifier.notifyDownloadSpeed(mInfo.mId, 0);
    }
}

From source file:com.akop.bach.ImageCache.java

public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    while (true) {
        try {/* w  w w.j  av a 2s  .c o m*/
            mCurrentTask = mTasks.take();
            if (mCurrentTask.alwaysRun || mListeners.contains(mCurrentTask.listener)) {
                mBusy = true;

                // Load bitmap
                Bitmap bmp = loadBitmapSynchronous(mCurrentTask.imageUrl, mCurrentTask.cachePol);

                if (mCurrentTask.alwaysRun || mListeners.contains(mCurrentTask.listener))
                    mCurrentTask.listener.onImageReady(mCurrentTask.id, mCurrentTask.param, bmp);

                mCurrentTask = null;
            }
        } catch (Exception e) {
            if (App.getConfig().logToConsole()) {
                App.logv("Error running task", e);
                e.printStackTrace();
            }
        }

        mBusy = false;
    }
}

From source file:com.ifeng.util.download.DownloadThread.java

/**
 * Executes the download in a separate thread
 *//*from   w  w  w.  j av a 2 s  .c  om*/
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    State state = new State(mInfo);
    ProxyHttpClient client = null;
    PowerManager.WakeLock wakeLock = null;
    int finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR;

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

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

        client = new ProxyHttpClient(mContext, userAgent());
        boolean finished = false;
        while (!finished) {
            Log.i(Constants.TAG, "Initiating request for download " + mInfo.mId);
            HttpGet request = new HttpGet(state.mRequestUri.trim());
            try {
                executeDownload(state, client, request);
                finished = true;
            } catch (RetryDownload exc) {
                // fall through
                exc.printStackTrace();
            } finally {
                request.abort();
                request = null;
            }
        }

        if (Constants.LOGV) {
            Log.v(Constants.TAG, "download completed for " + mInfo.mUri);
        }
        finalizeDestinationFile(state);
        finalStatus = Downloads.Impl.STATUS_SUCCESS;
    } catch (StopRequest error) {
        // remove the cause before printing, in case it contains PII
        Log.w(Constants.TAG, "Aborting request for download " + mInfo.mId + ": " + error.getMessage());
        Log.w(Constants.TAG, "download error:", error);
        finalStatus = error.mFinalStatus;
        displayMsg(finalStatus, error.getMessage());
        // 
        mInfo.mFailedReason = mInfo.mFailedReason + " |||| " + Utils.getStackTraceString(error);
        // fall through to finally block
    } catch (Throwable ex) { // sometimes the socket code throws unchecked
        // exceptions
        Log.w(Constants.TAG, "Exception for id " + mInfo.mId + ": " + ex);
        Log.w(Constants.TAG, "download error:", ex);
        finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR;
        displayMsg(finalStatus, ex.getMessage());
        // 
        mInfo.mFailedReason = mInfo.mFailedReason + "||||" + Utils.getStackTraceString(ex);
        // falls through to the code that reports an error
    } finally {
        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
        if (client != null) {
            client.close();
            client = null;
        }
        cleanupDestination(state, finalStatus);

        notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mRedirectCount,
                state.mGotData, state.mFilename, state.mNewUri, state.mMimeType);

        --DownloadService.mCurrentThreadNum;
        if (!Downloads.Impl.isStatusCompleted(finalStatus)) {
            mInfo.mHasActiveThread = false;
        }
    }
}

From source file:com.github.diogochbittencourt.googleplaydownloader.downloader.impl.DownloadThread.java

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

    State state = new State(mInfo, mService);
    AndroidHttpClient client = null;
    PowerManager.WakeLock wakeLock = null;
    int finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR;

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

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

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

        boolean finished = false;
        while (!finished) {
            if (Constants.LOGV) {
                Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName);
                Log.v(Constants.TAG, "  at " + mInfo.mUri);
            }
            // Set or unset proxy, which may have changed since last GET
            // request.
            // setDefaultProxy() supports null as proxy parameter.
            ConnRouteParams.setDefaultProxy(client.getParams(),
                    getPreferredHttpHost(mContext, state.mRequestUri));
            HttpGet request = new HttpGet(state.mRequestUri);
            try {
                executeDownload(state, client, request);
                finished = true;
            } catch (RetryDownload exc) {
                // fall through
            } finally {
                request.abort();
                request = null;
            }
        }

        if (Constants.LOGV) {
            Log.v(Constants.TAG, "download completed for " + mInfo.mFileName);
            Log.v(Constants.TAG, "  at " + mInfo.mUri);
        }
        finalizeDestinationFile(state);
        finalStatus = DownloaderService.STATUS_SUCCESS;
    } catch (StopRequest error) {
        // remove the cause before printing, in case it contains PII
        Log.w(Constants.TAG, "Aborting request for download " + mInfo.mFileName + ": " + error.getMessage());
        error.printStackTrace();
        finalStatus = error.mFinalStatus;
        // fall through to finally block
    } catch (Throwable ex) { // sometimes the socket code throws unchecked
        // exceptions
        Log.w(Constants.TAG, "Exception for " + mInfo.mFileName + ": " + ex);
        finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR;
        // falls through to the code that reports an error
    } finally {
        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
        if (client != null) {
            client.close();
            client = null;
        }
        cleanupDestination(state, finalStatus);
        notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mRedirectCount,
                state.mGotData, state.mFilename);
    }
}

From source file:com.google.android.vending.expansion.downloader.impl.DownloadThread.java

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

    State state = new State(mInfo, mService);
    AndroidHttpClient client = null;
    PowerManager.WakeLock wakeLock = null;
    int finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR;

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

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

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

        boolean finished = false;
        while (!finished) {
            if (Constants.LOGV) {
                Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName);
                Log.v(Constants.TAG, "  at " + mInfo.mUri);
            }
            // Set or unset proxy, which may have changed since last GET
            // request.
            // setDefaultProxy() supports null as proxy parameter.
            ConnRouteParams.setDefaultProxy(client.getParams(),
                    getPreferredHttpHost(mContext, state.mRequestUri));
            HttpGet request = new HttpGet(state.mRequestUri);
            try {
                executeDownload(state, client, request);
                finished = true;
            } catch (RetryDownload exc) {
                // fall through
            } finally {
                request.abort();
                request = null;
            }
        }

        if (Constants.LOGV) {
            Log.v(Constants.TAG, "download completed for " + mInfo.mFileName);
            Log.v(Constants.TAG, "  at " + mInfo.mUri);
        }
        finalizeDestinationFile(state);
        finalStatus = DownloaderService.STATUS_SUCCESS;
    } catch (StopRequest error) {
        // remove the cause before printing, in case it contains PII
        Log.w(Constants.TAG, "Aborting request for download " + mInfo.mFileName + ": " + error.getMessage());
        error.printStackTrace();
        finalStatus = error.mFinalStatus;
        // fall through to finally block
    } catch (Throwable ex) { // sometimes the socket code throws unchecked
                             // exceptions
        Log.w(Constants.TAG, "Exception for " + mInfo.mFileName + ": " + ex);
        finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR;
        // falls through to the code that reports an error
    } finally {
        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
        if (client != null) {
            client.close();
            client = null;
        }
        cleanupDestination(state, finalStatus);
        notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mRedirectCount,
                state.mGotData, state.mFilename);
    }
}

From source file:com.rowland.hashtrace.utility.AsyncTaskEx.java

/**
 * Creates a new asynchronous task. This constructor must be invoked on the
 * UI thread./*from  w  ww .  j  av  a 2s  .c  o  m*/
 */
public AsyncTaskEx() {
    mWorker = new WorkerRunnable<Params, Result>() {
        @Override
        public Result call() throws Exception {
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            return doInBackground(mParams);
        }
    };

    mFuture = new FutureTask<Result>(mWorker) {
        @SuppressWarnings("unchecked")
        @Override
        protected void done() {
            Message message;
            Result result = null;

            try {
                result = get();
            } catch (InterruptedException e) {
                android.util.Log.w(LOG_TAG, e);
            } catch (ExecutionException e) {
                throw new RuntimeException("An error occured while executing doInBackground()", e.getCause());
            } catch (CancellationException e) {
                message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,
                        new AsyncTaskExResult<Result>(AsyncTaskEx.this, (Result[]) null));
                message.sendToTarget();
                return;
            } catch (Throwable t) {
                throw new RuntimeException("An error occured while executing " + "doInBackground()", t);
            }

            message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
                    new AsyncTaskExResult<Result>(AsyncTaskEx.this, result));
            message.sendToTarget();
        }
    };
}

From source file:com.syncedsynapse.kore2.jsonrpc.HostConnection.java

/**
* Calls the a method on the server//from ww  w  .ja v a2  s.c  o m
* This call is always asynchronous. The results will be posted, through the
* {@link ApiCallback callback} parameter, on the specified {@link android.os.Handler}.
*
* @param method Method object that represents the methood too call
* @param callback {@link ApiCallback} to post the response to
* @param handler {@link Handler} to invoke callbacks on
* @param <T> Method return type
*/
public <T> void execute(final ApiMethod<T> method, final ApiCallback<T> callback, final Handler handler) {
    LogUtils.LOGD(TAG, "Starting method execute. Method: " + method.getMethodName() + " on host: "
            + hostInfo.getJsonRpcHttpEndpoint());

    // Launch background thread
    Runnable command = new Runnable() {
        @Override
        public void run() {
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            if (protocol == PROTOCOL_HTTP) {
                executeThroughHTTP(method, callback, handler);
            } else {
                executeThroughTcp(method, callback, handler);
            }
        }
    };

    executorService.execute(command);
    //new Thread(command).start();
}

From source file:org.xbmc.kore.jsonrpc.HostConnection.java

/**
* Calls the a method on the server/*from  www .ja  v  a  2  s . co m*/
* This call is always asynchronous. The results will be posted, through the
* {@link ApiCallback callback} parameter, on the specified {@link android.os.Handler}.
*
* @param method Method object that represents the methood too call
* @param callback {@link ApiCallback} to post the response to
* @param handler {@link Handler} to invoke callbacks on
* @param <T> Method return type
*/
public <T> void execute(final ApiMethod<T> method, final ApiCallback<T> callback, final Handler handler) {
    LogUtils.LOGD(TAG, "Starting method execute. Method: " + method.getMethodName() + " on host: "
            + hostInfo.getJsonRpcHttpEndpoint());

    // Launch background thread
    Runnable command = new Runnable() {
        @Override
        public void run() {
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            if (protocol == PROTOCOL_HTTP) {
                //                    executeThroughHttp(method, callback, handler);
                executeThroughOkHttp(method, callback, handler);
            } else {
                executeThroughTcp(method, callback, handler);
            }
        }
    };

    executorService.execute(command);
    //new Thread(command).start();
}