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:ca.mcgill.hs.uploader.UploadThread.java

/**
 * Executes the upload in a separate thread
 *///from   w  w w.jav  a 2  s. c  o m

@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.owncloud.android.ui.notifications.NotificationUtils.java

public static void cancelWithDelay(final NotificationManager notificationManager, final int notificationId,
        long delayInMillis) {

    HandlerThread thread = new HandlerThread(
            "NotificationDelayerThread_" + (new Random(System.currentTimeMillis())).nextInt(),
            Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();// w ww.  j  a v  a2  s .c o  m

    Handler handler = new Handler(thread.getLooper());
    handler.postDelayed(new Runnable() {
        public void run() {
            notificationManager.cancel(notificationId);
            ((HandlerThread) Thread.currentThread()).getLooper().quit();
        }
    }, delayInMillis);

}

From source file:com.tenkiv.tekdaqc.android.services.DiscoveryService.java

@Override
public void onCreate() {
    super.onCreate();
    HandlerThread thread = new HandlerThread("TekDAQC Discovery Service", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();//w  w  w  .j  a v a2s .c om

    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper, this);
    mLocalBroadcastMgr = LocalBroadcastManager.getInstance(getApplicationContext());

    Locator.setDebug(true);
}

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

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

    /*//from w ww  .jav a 2  s . co  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  ww .ja v a  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.amgems.uwschedule.services.LoginService.java

@Override
public void onCreate() {
    HandlerThread handlerThread = new HandlerThread("HANDLERTHREAD", Process.THREAD_PRIORITY_BACKGROUND);
    handlerThread.start();//from  ww w . j a va2s  .c  om

    mServiceLooper = handlerThread.getLooper();
    mHandler = new LoginHandler(mServiceLooper);
}

From source file:org.durka.hallmonitor.CoreService.java

@Override
public void onCreate() {
    Log.d(LOG_TAG + ".oC", "Core service creating");
    localCoreService = this;

    mStateManager = ((CoreApp) getApplicationContext()).getStateManager();

    Log.d(LOG_TAG + ".oC", "Register special actions");
    mStateManager.registerCoreService(this);

    mStateManager.registerCoreReceiver();

    mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);

    HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();//from   w  w w.  ja  va  2 s  .c o  m

    // Get the HandlerThread's Looper and use it for our Handler
    mTouchCoverLooper = thread.getLooper();
    mTouchCoverHandler = new TouchCoverHandler(mTouchCoverLooper);
    lastTouchCoverRequest = mStateManager.getCoverClosed();

    try {
        startActivityAsUser = ((ContextWrapper) this).getClass().getMethod("startActivityAsUser", Intent.class,
                UserHandle.class);
        Log.d(LOG_TAG, "startActivityAsUser registred");
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }

    launchDefaultActivity = new Intent(localCoreService, DefaultActivity.class)
            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION
                    | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);

    mUserHandle = android.os.Process.myUserHandle();
}

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

@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;//from   w  w w  .jav a 2  s . c  om
    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.tenkiv.tekdaqc.android.services.CommunicationService.java

@Override
public void onCreate() {
    super.onCreate();
    Log.d(TAG, "CommunicationService onCreate()");

    // Setup the background thread and its controls
    HandlerThread thread = new HandlerThread("TekDAQC Communication Service",
            Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();/*from  www. j a  v  a  2 s .com*/

    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper, this);
    mLocalBroadcastMgr = LocalBroadcastManager.getInstance(getApplicationContext());

    // Initialize the session map
    mCommSessions = new ConcurrentHashMap<String, ASCIICommunicationSession>();
}

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

@Override
public void run() {
    if (DEBUG)/*from   w  w  w . ja v  a 2s  .  c o m*/
        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;
        }
    }
}