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:com.digitalarx.android.files.services.FileUploader.java

/**
 * Service initialization// ww  w .  j a  va  2 s  . c o m
 */
@Override
public void onCreate() {
    super.onCreate();
    Log_OC.i(TAG, "mPendingUploads size:" + mPendingUploads.size());
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    HandlerThread thread = new HandlerThread("FileUploaderThread", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper, this);
    mBinder = new FileUploaderBinder();
}

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

/**
 * Executes the download in a separate thread
 *///from w ww.  j a va2s  .  c  o 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.google.android.vending.expansion.downloader.impl.DownloadThread.java

/**
 * Executes the download in a separate thread
 *//* w ww  . j a  va  2  s. c o 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:de.schildbach.wallet.ui.scan.ScanActivity.java

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

    viewModel = ViewModelProviders.of(this).get(ScanViewModel.class);
    viewModel.showPermissionWarnDialog.observe(this, new Observer<Void>() {
        @Override//  w  ww .j a  v a  2s.  c  o  m
        public void onChanged(final Void v) {
            WarnDialogFragment.show(getSupportFragmentManager(), R.string.scan_camera_permission_dialog_title,
                    getString(R.string.scan_camera_permission_dialog_message));
        }
    });
    viewModel.showProblemWarnDialog.observe(this, new Observer<Void>() {
        @Override
        public void onChanged(final Void v) {
            WarnDialogFragment.show(getSupportFragmentManager(), R.string.scan_camera_problem_dialog_title,
                    getString(R.string.scan_camera_problem_dialog_message));
        }
    });

    // Stick to the orientation the activity was started with. We cannot declare this in the
    // AndroidManifest.xml, because it's not allowed in combination with the windowIsTranslucent=true
    // theme attribute.
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
    // Draw under navigation and status bars.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
                WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

    setContentView(R.layout.scan_activity);
    contentView = findViewById(android.R.id.content);
    scannerView = (ScannerView) findViewById(R.id.scan_activity_mask);
    previewView = (TextureView) findViewById(R.id.scan_activity_preview);
    previewView.setSurfaceTextureListener(this);

    cameraThread = new HandlerThread("cameraThread", Process.THREAD_PRIORITY_BACKGROUND);
    cameraThread.start();
    cameraHandler = new Handler(cameraThread.getLooper());

    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA }, 0);

    if (savedInstanceState == null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        final Intent intent = getIntent();
        final int x = intent.getIntExtra(INTENT_EXTRA_SCENE_TRANSITION_X, -1);
        final int y = intent.getIntExtra(INTENT_EXTRA_SCENE_TRANSITION_Y, -1);
        if (x != -1 || y != -1) {
            // Using alpha rather than visibility because 'invisible' will cause the surface view to never
            // start up, so the animation will never start.
            contentView.setAlpha(0);
            getWindow().setBackgroundDrawable(
                    new ColorDrawable(getResources().getColor(android.R.color.transparent)));
            OnFirstPreDraw.listen(contentView, new OnFirstPreDraw.Callback() {
                @Override
                public boolean onFirstPreDraw() {
                    float finalRadius = (float) (Math.max(contentView.getWidth(), contentView.getHeight()));
                    final int duration = getResources().getInteger(android.R.integer.config_mediumAnimTime);
                    sceneTransition = ViewAnimationUtils.createCircularReveal(contentView, x, y, 0,
                            finalRadius);
                    sceneTransition.setDuration(duration);
                    sceneTransition.setInterpolator(new AccelerateInterpolator());
                    // TODO Here, the transition should start in a paused state, showing the first frame
                    // of the animation. Sadly, RevealAnimator doesn't seem to support this, unlike
                    // (subclasses of) ValueAnimator.
                    return false;
                }
            });
        }
    }
}

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

/**
 * Creates a new asynchronous task. This constructor must be invoked on the
 * UI thread./* w  w  w .  j ava2 s .c om*/
 */
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.owncloud.android.services.OperationsService.java

/**
 * Service initialization/*  w ww  .  ja  va 2 s.c o m*/
 */
@Override
public void onCreate() {
    super.onCreate();
    Log_OC.d(TAG, "Creating service");

    /// First worker thread for most of operations 
    HandlerThread thread = new HandlerThread("Operations thread", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();
    mOperationsHandler = new ServiceHandler(thread.getLooper(), this);
    mOperationsBinder = new OperationsServiceBinder(mOperationsHandler);

    /// Separated worker thread for download of folders (WIP)
    thread = new HandlerThread("Syncfolder thread", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();
    mSyncFolderHandler = new SyncFolderHandler(thread.getLooper(), this);

    // create manager for local broadcasts
    mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
}

From source file:com.uphyca.idobata.android.service.IdobataService.java

private void ensureHandler() {
    HandlerThread t = new HandlerThread("IdobataService", Process.THREAD_PRIORITY_BACKGROUND);
    t.start();// w  ww . j  a  v a  2s . c  o  m
    mServiceLooper = t.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
}

From source file:com.speedtong.example.ui.chatting.ChattingActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    LogUtil.d(TAG, "onCreate");
    super.onCreate(savedInstanceState);
    brand = Build.MODEL + Build.BRAND;/*from ww w. j  av a2  s .  c om*/
    TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    uuid = tm.getDeviceId();
    messageDao = MessageDao.getInstance(this);
    toast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
    sdpath = Environment.getExternalStorageDirectory().getAbsolutePath();

    // ???
    initView();
    // ???
    initActivityState(savedInstanceState);

    final ArrayList<ECMessage> list = IMessageSqlManager.queryIMessageList(mThread, 20,
            getMessageAdapterLastMessageTime() + "");
    mListView.post(new Runnable() {

        @Override
        public void run() {
            mChattingAdapter.setData(list);
            if (mChattingAdapter.getCount() < 20) {
                //mPullDownView.setPullEnabled(false);
                //mPullDownView.setPullViewVisibed(false);
            }
            mListView.clearFocus();
            mChattingAdapter.notifyDataSetChanged();
            mListView.setSelection(mChattingAdapter.getCount());
        }
    });

    // ?IM?API
    mChatManager = SDKCoreHelper.getECChatManager();
    HandlerThread thread = new HandlerThread("ChattingVoiceRecord", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();

    // Get the HandlerThread's Looper and use it for our Handler
    mChattingLooper = thread.getLooper();
    mVoiceHandler = new Handler(mChattingLooper);
    mVoiceHandler.post(new Runnable() {

        @Override
        public void run() {
            doEmojiPanel();
        }
    });
}

From source file:paulscode.android.mupen64plusae.task.CacheRomInfoService.java

@Override
public void onCreate() {
    // Start up the thread running the service.  Note that we create a
    // separate thread because the service normally runs in the process's
    // main thread, which we don't want to block.  We also make it
    // background priority so CPU-intensive work will not disrupt our UI.
    HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();/*from w  ww. j a  v  a  2  s. c  o  m*/

    // Get the HandlerThread's Looper and use it for our Handler
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);

    //Show the notification
    Intent notificationIntent = new Intent(this, GalleryActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.icon)
            .setContentTitle(getString(R.string.scanning_title))
            .setContentText(getString(R.string.toast_pleaseWait)).setContentIntent(pendingIntent);
    startForeground(ONGOING_NOTIFICATION_ID, builder.build());
}