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:Main.java

public static void setThreadPriority(boolean z) {
    if (z) {/*www.  j a  va 2s  .  c o m*/
        Process.setThreadPriority(-2);
    } else {
        Process.setThreadPriority(10);
    }
}

From source file:ca.mcgill.hs.uploader.UploadThread.java

/**
 * Executes the upload in a separate thread
 *///  w  w w .java  2s . com

@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    int finalStatus = Constants.STATUS_UNKNOWN_ERROR;
    boolean countRetry = false;
    int retryAfter = 0;
    AndroidHttpClient client = null;
    PowerManager.WakeLock wakeLock = null;
    String filename = null;

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

            filename = mInfo.mFileName;
            final File file = new File(filename);
            if (!file.exists()) {
                Log.e(Constants.TAG, "file" + filename + " is to be uploaded, but cannot be found.");
                finalStatus = Constants.STATUS_FILE_ERROR;
                break http_request_loop;
            }
            client = AndroidHttpClient.newInstance(Constants.DEFAULT_USER_AGENT, mContext);
            Log.v(Constants.TAG, "initiating upload for " + mInfo.mUri);
            final HttpPost request = new HttpPost(Constants.UPLOAD_URL);
            request.addHeader("MAC", NetworkHelper.getMacAddress(mContext));

            final MultipartEntity mpEntity = new MultipartEntity();
            mpEntity.addPart("uploadedfile", new FileBody(file, "binary/octet-stream"));
            request.setEntity(mpEntity);

            HttpResponse response;
            try {
                response = client.execute(request);
                final HttpEntity resEntity = response.getEntity();

                String responseMsg = null;
                if (resEntity != null) {
                    responseMsg = EntityUtils.toString(resEntity);
                    Log.i(Constants.TAG, "Server Response: " + responseMsg);
                }
                if (resEntity != null) {
                    resEntity.consumeContent();
                }

                if (!responseMsg.contains("SUCCESS 0x64asv65")) {
                    Log.i(Constants.TAG, "Server Response: " + responseMsg);
                }
            } catch (final IllegalArgumentException e) {
                finalStatus = Constants.STATUS_BAD_REQUEST;
                request.abort();
                break http_request_loop;
            } catch (final IOException e) {
                if (!NetworkHelper.isNetworkAvailable(mContext)) {
                    finalStatus = Constants.STATUS_RUNNING_PAUSED;
                } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) {
                    finalStatus = Constants.STATUS_RUNNING_PAUSED;
                    countRetry = true;
                } else {
                    Log.d(Constants.TAG, "IOException trying to excute request for " + mInfo.mUri + " : " + e);
                    finalStatus = Constants.STATUS_HTTP_DATA_ERROR;
                }
                request.abort();
                break http_request_loop;
            }

            final int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 503 && mInfo.mNumFailed < Constants.MAX_RETRIES) {
                Log.v(Constants.TAG, "got HTTP response code 503");
                finalStatus = Constants.STATUS_RUNNING_PAUSED;
                countRetry = true;

                retryAfter = Constants.MIN_RETRY_AFTER;
                retryAfter += NetworkHelper.sRandom.nextInt(Constants.MIN_RETRY_AFTER + 1);
                retryAfter *= 1000;
                request.abort();
                break http_request_loop;
            } else {
                finalStatus = Constants.STATUS_SUCCESS;
            }
            break;
        } catch (final RuntimeException e) {
            finalStatus = Constants.STATUS_UNKNOWN_ERROR;
        } finally {
            mInfo.mHasActiveThread = false;
            if (wakeLock != null) {
                wakeLock.release();
                wakeLock = null;
            }
            if (client != null) {
                client.close();
                client = null;
            }
            if (finalStatus == Constants.STATUS_SUCCESS) {
                // TODO: Move the file.
            }
        }
    }

}

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

@Override
protected void onHandleIntent(Intent intent) {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    /*/*w ww  .  ja  v  a 2  s  . c  o  m*/
     * Obtain the FirebaseAnalytics instance.
     */
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

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

    String filename1 = extras.getString("lname");
    String filename2 = extras.getString("rname");

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

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

    int facing = extras.getInt(MainConsts.EXTRA_FACING);
    boolean isFrontCamera = (facing == Camera.CameraInfo.CAMERA_FACING_FRONT) ? true : false;

    String[] stereoPath = MediaScanner.getImgPairPaths(filename1, filename2);

    if (stereoPath == null) {
        /*
         * something seriously wrong here - can't find matching image
         */
        if (BuildConfig.DEBUG)
            Log.e(TAG, "onHandleEvent: cannot locate stereo image pair");
        reportError(MediaScanner.getProcessedSbsPath(filename1));
        return;
    }

    if (BuildConfig.DEBUG)
        Log.d(TAG,
                "onHandleIntent:stereoPath[0]=" + stereoPath[0] + ",stereoPath[1]=" + stereoPath[1]
                        + ",stereoPath[2]=" + stereoPath[2] + ",stereoPath[3]=" + stereoPath[3]
                        + ",stereoPath[4]=" + stereoPath[4]);

    /*
     * now do auto alignment and store images as full width sbs jpgs. 
     * original left/right images will be removed unless save flag
     * is set to true (for debugging)
     */
    boolean[] success = new boolean[] { false, false };
    try {
        success = p.getInstance().b(stereoPath[0], stereoPath[1], stereoPath[2], scale, isFrontCamera);
    } catch (RuntimeException e) {
        e.printStackTrace();
    }

    if (!success[0]) {
        reportError(stereoPath[2]);
    } else {
        saveThumbnail(stereoPath[2], MainConsts.MEDIA_3D_THUMB_PATH + (new File(stereoPath[2])).getName());

        MediaScanner.insertExifInfo(stereoPath[2], "name=" + creatorName + "photourl=" + creatorPhotoUrl);

        reportResult(stereoPath[2], success[1]);
    }

    File leftFrom = new File(stereoPath[0]);
    File rightFrom = new File(stereoPath[1]);

    if (!BuildConfig.DEBUG) {
        leftFrom.delete();
        rightFrom.delete();
    } else {
        File leftTo = new File(stereoPath[3]);
        File rightTo = new File(stereoPath[4]);

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

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

@Override
protected void onHandleIntent(Intent intent) {
    if (BuildConfig.DEBUG)
        Log.d(TAG, "onHandleIntent");

    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    Resources res = getResources();
    String httpDir = res.getString(R.string.samples_link_dir_name);

    /*//from w w w .  j  ava  2 s. c o  m
     * to avoid hitting file access limits in google drive, we duplicated samples
     * to 10 accounts. the links are stored in samples[1-10].lnk
     */
    Random rand = new Random();
    int n = rand.nextInt(10) + 1;
    if (BuildConfig.DEBUG)
        Log.d(TAG, "onHandleIntent: sample link file #" + n);

    String samplesLinkFilename = res.getString(R.string.samples_link_file_name) + Integer.toString(n) + "."
            + MainConsts.LINK_EXTENSION;

    String url = "https://" + res.getString(R.string.app_domain) + "/" + httpDir + "/" + samplesLinkFilename;

    String saveLinkFilename = res.getString(R.string.samples_link_file_name) + "." + MainConsts.LINK_EXTENSION;
    String path = MainConsts.MEDIA_3D_ROOT_PATH + saveLinkFilename;

    /*
     * download the link file
     */
    DownloadFileTask dft = new DownloadFileTask(this, url, path);
    dft.execute();

    boolean isSuccess = false;

    /*
     * wait for the asynctask to be done
     */
    try {
        isSuccess = dft.get();
    } catch (InterruptedException e) {
        return;
    } catch (ExecutionException e) {
        return;
    }

    /*
     * parse the link file and decide which ones (if any) need to be downloaded
     */
    if (isSuccess) {
        if (BuildConfig.DEBUG)
            Log.d(TAG, "onHandleIntent: download link file success");
        parseLinkFile(path);
    } else {
        if (BuildConfig.DEBUG)
            Log.d(TAG, "onHandleIntent: unable to download link file");
    }
}

From source file:com.eTilbudsavis.etasdk.network.NetworkDispatcher.java

@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;/*from  w  ww . j av a2 s.co  m*/
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            // We may have been interrupted because it was time to quit.
            if (mQuit) {
                return;
            }
            continue;
        }

        try {

            // If the request was cancelled already, do not perform the network request.
            if (request.isCanceled()) {
                request.finish("network-dispatcher-cancelled-on-recieved");
                continue;
            } else {
                request.addEvent("recieved-by-network-dispatcher");
            }

            prepare(request);

            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);

            appendLogging(request, networkResponse);

            request.addEvent("parsing-network-response");
            Response<?> response = request.parseNetworkResponse(networkResponse);

            if (response.isSuccess()) {

                updateSessionInfo(networkResponse.headers);
                mCache.put(request, response);
                mDelivery.postResponse(request, response);

            } else {

                if (SessionManager.recoverableError(response.error)) {

                    request.addEvent("recoverable-session-error");

                    if (isSessionEndpoint(request)) {

                        mDelivery.postResponse(request, response);

                    } else {

                        // Query the session manager to perform an update
                        if (mEta.getSessionManager().recover(response.error)) {
                            mRequestQueue.add(request);
                        } else {
                            mDelivery.postResponse(request, response);
                        }

                    }

                } else {

                    request.addEvent("non-recoverable-error");
                    mDelivery.postResponse(request, response);

                }

            }

        } catch (EtaError e) {

            request.addEvent("network-error");
            mDelivery.postResponse(request, Response.fromError(e));

        }
    }
}

From source file:com.android.volley.CacheDispatcher.java

@Override
public void run() {
    if (DEBUG)// w w  w  . jav  a2 s  .c om
        VolleyLog.v("start new dispatcher");
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    // Make a blocking call to initialize the cache.
    mCache.initialize();

    while (true) {
        try {
            // Get a request from the cache triage queue, blocking until
            // at least one is available.
            final Request<?> request = mCacheQueue.take();
            request.addMarker("cache-queue-take");

            // If the request has been canceled, don't bother dispatching it.
            if (request.isCanceled()) {
                request.finish("cache-discard-canceled");
                continue;
            }

            // Attempt to retrieve this item from cache.
            Cache.Entry entry = mCache.get(request.getCacheKey());
            if (entry == null) {
                request.addMarker("cache-miss");
                // Cache miss; send off to the network dispatcher.
                mNetworkQueue.put(request);
                continue;
            }

            // If it is completely expired, just send it to the network.
            if (entry.isExpired()) {
                request.addMarker("cache-hit-expired");
                request.setCacheEntry(entry);
                mNetworkQueue.put(request);
                continue;
            }

            // We have a cache hit; parse its data for delivery back to the request.
            request.addMarker("cache-hit");
            Response<?> response = request
                    .parseNetworkResponse(new NetworkResponse(entry.data, entry.responseHeaders));
            request.addMarker("cache-hit-parsed");

            if (!entry.refreshNeeded()) {
                // Completely unexpired cache hit. Just deliver the response.
                mDelivery.postResponse(request, response);
            } else {
                // Soft-expired cache hit. We can deliver the cached response,
                // but we need to also send the request to the network for
                // refreshing.
                request.addMarker("cache-hit-refresh-needed");
                request.setCacheEntry(entry);

                // Mark the response as intermediate.
                response.intermediate = true;

                // Post the intermediate response back to the user and have
                // the delivery then forward the request along to the network.
                mDelivery.postResponse(request, response, new Runnable() {
                    @Override
                    public void run() {
                        try {
                            mNetworkQueue.put(request);
                        } catch (InterruptedException e) {
                            // Not much we can do about this.
                        }
                    }
                });
            }

        } catch (InterruptedException e) {
            // We may have been interrupted because it was time to quit.
            if (mQuit) {
                return;
            }
            continue;
        }
    }
}

From source file:com.android.volley.NetworkDispatcher.java

@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    while (true) {
        long startTimeMs = SystemClock.elapsedRealtime();
        Request<?> request;
        try {/*from   w  w  w . ja va  2 s.c om*/
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            // We may have been interrupted because it was time to quit.
            if (mQuit) {
                return;
            }
            continue;
        }

        try {
            request.addMarker("network-queue-take");

            // If the request was cancelled already, do not perform the
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }

            addTrafficStatsTag(request);

            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");

            // If the server returned 304 AND we delivered a response already,
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }

            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");

            // Write to cache if applicable.
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }

            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            VolleyError volleyError = new VolleyError(e);
            volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
            mDelivery.postError(request, volleyError);
        }
    }
}

From source file:com.siahmsoft.soundroid.sdk7.provider.tracks.TracksUpdater.java

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

    while (!mStopped) {
        try {/*from www .  j  a  v a  2  s .c om*/
            final String trackId = mQueue.take();

            final Long lastCheck = sLastChecks.get(trackId);

            if (lastCheck != null && lastCheck + ONE_DAY >= System.currentTimeMillis()) {
                continue;
            }

            sLastChecks.put(trackId, System.currentTimeMillis());

            final TracksStore.Track track = TracksManager.findTrack(mResolver, trackId);

            if (track.getmLastModified() == null || track.getmArtworkUrl() == null) {
                continue;
            }

            if (trackArtworkUpdated(track, expiring) && expiring.lastModified != null) {
                ImageUtilities.deleteCachedCover(trackId);
                final Bitmap bitmap = track.loadCover(TracksStore.ImageSize.TINY);
                ImportUtilities.addTrackCoverToCache(track, bitmap);

                mValues.put(TracksStore.Track.LAST_MODIFIED, expiring.lastModified.getTimeInMillis());
                mArguments[0] = trackId;
                mResolver.update(TracksStore.Track.CONTENT_URI, mValues, mSelection, mArguments);
            }

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

From source file:biz.varkon.shelvesom.provider.toys.ToysUpdater.java

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

    while (!mStopped) {
        try {/*from  ww w . ja  v a  2  s .  co m*/
            final String toyId = mQueue.take();

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

            final ToysStore.Toy toy = ToysManager.findToy(mResolver, toyId, null);

            if (toy == null)
                continue;

            final String imgURL = Preferences.getImageURLForUpdater(toy);

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

            if (toyCoverUpdated(toy, expiring) && expiring.lastModified != null) {
                ImageUtilities.deleteCachedCover(toyId);

                final Bitmap bitmap = Preferences.getBitmapForManager(toy);

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

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

                mValues.put(BaseItem.LAST_MODIFIED, expiring.lastModified.getTimeInMillis());
                mArguments[0] = toyId;
                mResolver.update(ToysStore.Toy.CONTENT_URI, mValues, mSelection, mArguments);
            }

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

From source file:biz.varkon.shelvesom.provider.tools.ToolsUpdater.java

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

    while (!mStopped) {
        try {//from   w  ww.ja v  a 2s.co  m
            final String toolId = mQueue.take();

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

            final ToolsStore.Tool tool = ToolsManager.findTool(mResolver, toolId, null);

            if (tool == null)
                continue;

            final String imgURL = Preferences.getImageURLForUpdater(tool);

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

            if (toolCoverUpdated(tool, expiring) && expiring.lastModified != null) {
                ImageUtilities.deleteCachedCover(toolId);

                final Bitmap bitmap = Preferences.getBitmapForManager(tool);

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

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

                mValues.put(BaseItem.LAST_MODIFIED, expiring.lastModified.getTimeInMillis());
                mArguments[0] = toolId;
                mResolver.update(ToolsStore.Tool.CONTENT_URI, mValues, mSelection, mArguments);
            }

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