Java Code Examples for android.os.Process#setThreadPriority()

The following examples show how to use android.os.Process#setThreadPriority() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CacheDispatcher.java    From volley with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    if (DEBUG) VolleyLog.v("start new dispatcher");
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

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

    while (true) {
        try {
            processRequest();
        } catch (InterruptedException e) {
            // We may have been interrupted because it was time to quit.
            if (mQuit) {
                Thread.currentThread().interrupt();
                return;
            }
            VolleyLog.e(
                    "Ignoring spurious interrupt of CacheDispatcher thread; "
                            + "use quit() to terminate it");
        }
    }
}
 
Example 2
Source File: VolumeAccessibilityService.java    From Noyze with Apache License 2.0 6 votes vote down vote up
@Override
protected void onServiceConnected() {
	if (isInfrastructureInitialized) { return; }
	super.onServiceConnected();
    LOGI(TAG, "onServiceConnected(pid=" + android.os.Process.myPid() +
            ", uid=" + Process.myUid() +
            ", tid=" + Process.myTid() + ")");

    mContext = this;
    mPreferences = SettingsHelper.getInstance(mContext);
    mPreferences.registerOnSharedPreferenceChangeListener(this);
    initServiceInfo();
    initPrefNames();
    pWindowManager = new PopupWindowManager(mContext);

    updateDisabledButtons(mPreferences.getSharedPreferences());
    updateMediaCloak();
    updateBlacklist();
    isInfrastructureInitialized = true;
    peekIntoTheNexus();
    Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_AUDIO);
    MainThreadBus.get().register(this);
    mHandler.sendEmptyMessage(MESSAGE_START);
}
 
Example 3
Source File: DeviceTest.java    From usb-serial-for-android with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void usbOpen(EnumSet<UsbOpenFlags> flags, int ioManagerTimeout) throws Exception {
    usbDeviceConnection = usbManager.openDevice(usbSerialDriver.getDevice());
    usbSerialPort = usbSerialDriver.getPorts().get(test_device_port);
    usbSerialPort.open(usbDeviceConnection);
    if(!flags.contains(UsbOpenFlags.NO_CONTROL_LINE_INIT)) {
        usbSerialPort.setDTR(true);
        usbSerialPort.setRTS(true);
    }
    if(!flags.contains(UsbOpenFlags.NO_IOMANAGER_THREAD)) {
        usbIoManager = new SerialInputOutputManager(usbSerialPort, this) {
            @Override
            public void run() {
                if (SERIAL_INPUT_OUTPUT_MANAGER_THREAD_PRIORITY != null)
                    Process.setThreadPriority(SERIAL_INPUT_OUTPUT_MANAGER_THREAD_PRIORITY);
                super.run();
            }
        };
        usbIoManager.setReadTimeout(ioManagerTimeout);
        usbIoManager.setWriteTimeout(ioManagerTimeout);
        Executors.newSingleThreadExecutor().submit(usbIoManager);
    }
    synchronized (usbReadBuffer) {
        usbReadBuffer.clear();
    }
    usbReadError = null;
}
 
Example 4
Source File: VideoPlayer.java    From Dashchan with Apache License 2.0 6 votes vote down vote up
private void init(InputHolder inputHolder) throws IOException {
	synchronized (inputLock) {
		if (pointer == 0 && !consumed) {
			int priority = Process.getThreadPriority(Process.myTid());
			Process.setThreadPriority(Process.THREAD_PRIORITY_DISPLAY);
			try {
				this.inputHolder = inputHolder;
				pointer = init(new NativeBridge(this), seekAnyFrame);
				int errorCode = getErrorCode(pointer);
				if (errorCode != 0) {
					free();
					throw new InitializationException(errorCode);
				}
				initialized = true;
				seekerThread.start();
			} finally {
				Process.setThreadPriority(priority);
			}
		}
	}
}
 
Example 5
Source File: AsyncTask.java    From document-viewer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
 */
public AsyncTask() {
    mWorker = new WorkerRunnable<Params, Result>() {

        @Override
        public Result call() throws Exception {
            mTaskInvoked.set(true);

            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            return postResult(doInBackground(mParams));
        }
    };

    mFuture = new FutureTask<Result>(mWorker) {

        @Override
        protected void done() {
            try {
                final Result result = get();

                postResultIfNotInvoked(result);
            } catch (final InterruptedException e) {
                android.util.Log.w(LOG_TAG, e);
            } catch (final ExecutionException e) {
                throw new RuntimeException("An error occured while executing doInBackground()", e.getCause());
            } catch (final CancellationException e) {
                postResultIfNotInvoked(null);
            } catch (final Throwable t) {
                throw new RuntimeException("An error occured while executing " + "doInBackground()", t);
            }
        }
    };
}
 
Example 6
Source File: SocketThread.java    From Cangol-appcore with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_AUDIO);
    while (isConnecting && !socketHandler.isInterrupted()) {
        synchronized (socketHandler.readLocker) {
            handleSocketRead();
        }
    }
}
 
Example 7
Source File: WorkerRunnable.java    From TaskQueue with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    try {
        if (mTask.isCanceled() || mTask.isTimeout() || mTask.hasHadResultDelivered()) {
            mTask.finish();
            return;
        }
        Result<?> result = mTask.execute();
        mDelivery.postResult(mTask, result);
    } catch (Throwable error) {
        mDelivery.postError(mTask, error);
    }
}
 
Example 8
Source File: AsyncTask.java    From UltimateAndroid with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
 */
public AsyncTask() {
    mWorker = new WorkerRunnable<Params, Result>() {
        public Result call() throws Exception {
            mTaskInvoked.set(true);

            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            return postResult(doInBackground(mParams));
        }
    };

    mFuture = new FutureTask<Result>(mWorker) {
        @Override
        protected void done() {
            try {
                final Result result = get();

                postResultIfNotInvoked(result);
            } 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) {
                postResultIfNotInvoked(null);
            } catch (Throwable t) {
                throw new RuntimeException("An error occured while executing "
                        + "doInBackground()", t);
            }
        }
    };
}
 
Example 9
Source File: ModernAsyncTask.java    From V.FlyoutTest with MIT License 5 votes vote down vote up
/**
 * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
 */
public ModernAsyncTask() {
    mWorker = new WorkerRunnable<Params, Result>() {
        public Result call() throws Exception {
            mTaskInvoked.set(true);

            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            return postResult(doInBackground(mParams));
        }
    };

    mFuture = new FutureTask<Result>(mWorker) {
        @Override
        protected void done() {
            try {
                final Result result = get();

                postResultIfNotInvoked(result);
            } 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) {
                postResultIfNotInvoked(null);
            } catch (Throwable t) {
                throw new RuntimeException("An error occured while executing "
                        + "doInBackground()", t);
            }
        }
    };
}
 
Example 10
Source File: AsyncTask.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
 */
public AsyncTask() {
    mWorker = new WorkerRunnable<Params, Result>() {
        public Result call() throws Exception {
            mTaskInvoked.set(true);

            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            //noinspection unchecked
            return postResult(doInBackground(mParams));
        }
    };

    mFuture = new FutureTask<Result>(mWorker) {
        @Override
        protected void done() {
            try {
                postResultIfNotInvoked(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) {
                postResultIfNotInvoked(null);
            }
        }
    };
}
 
Example 11
Source File: AsyncTask.java    From Reader with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
 */
public AsyncTask() {
    mWorker = new WorkerRunnable<Params, Result>() {
        public Result call() throws Exception {
            mTaskInvoked.set(true);

            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            //noinspection unchecked
            return postResult(doInBackground(mParams));
        }
    };

    mFuture = new FutureTask<Result>(mWorker) {
        @Override
        protected void done() {
            try {
                postResultIfNotInvoked(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) {
                postResultIfNotInvoked(null);
            }
        }
    };
}
 
Example 12
Source File: AsyncTask.java    From FanXin-based-HuanXin with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a new asynchronous task. This constructor must be invoked on the
 * UI thread.
 */
public AsyncTask() {
	mWorker = new WorkerRunnable<Params, Result>() {
		public Result call() throws Exception {
			mTaskInvoked.set(true);

			Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
			// noinspection unchecked
			return postResult(doInBackground(mParams));
		}
	};

	mFuture = new FutureTask<Result>(mWorker) {
		@Override
		protected void done() {
			try {
				postResultIfNotInvoked(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) {
				postResultIfNotInvoked(null);
			}
		}
	};

}
 
Example 13
Source File: DataRepository.java    From call_manage with MIT License 5 votes vote down vote up
public void deleteCGroup(long listId) {
    Thread thread = new Thread(() -> {
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        mDatabase.getCGroupDao().deleteById(listId);
    });
    thread.start();
}
 
Example 14
Source File: DownloadThread.java    From UnityOBBDownloader with Apache License 2.0 4 votes vote down vote up
/**
 * Executes the download in a separate thread
 */
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    State state = new State(mInfo, mService);
    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);
        }

        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.
            URL url = new URL(state.mRequestUri);
            HttpURLConnection request = (HttpURLConnection)url.openConnection();
            request.setRequestProperty("User-Agent", userAgent());
            try {
                executeDownload(state, request);
                finished = true;
            } catch (RetryDownload exc) {
                // fall through
            } finally {
                request.disconnect();
                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;
        }
        cleanupDestination(state, finalStatus);
        notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter,
                state.mRedirectCount, state.mGotData, state.mFilename);
    }
}
 
Example 15
Source File: BallCacheDispatcher.java    From Volley-Ball with MIT License 4 votes vote down vote up
@Override
public void run() {
    if (DEBUG) 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 BallRequest 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.
                //mDelivery.postEmptyIntermediateResponse(request, BallResponse.ResponseSource.CACHE);
                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);
                //mDelivery.postEmptyIntermediateResponse(request, BallResponse.ResponseSource.CACHE);
                mNetworkQueue.put(request);
                continue;
            }

            // We have a cache hit; parse its data for delivery back to the request.
            request.addMarker("cache-hit");
            BallResponse<?> response = request.getNetworkRequestProcessor().parseNetworkResponse(new NetworkResponse(entry.data, entry.responseHeaders));
            response.setResponseSource(BallResponse.ResponseSource.CACHE);
            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.setIntermediate(true);

                // Post the intermediate response back to the user and have
                // the delivery then forward the request along to the network.
                mDelivery.postResponseAndForwardToNetwork(request, response);
            }

        } catch (InterruptedException e) {
            // We may have been interrupted because it was time to quit.
            if (mQuit) {
                return;
            }
            continue;
        }
    }
}
 
Example 16
Source File: ThreadUtils.java    From cronet with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Set thread priority to audio.
 */
@CalledByNative
public static void setThreadPriorityAudio(int tid) {
    Process.setThreadPriority(tid, Process.THREAD_PRIORITY_AUDIO);
}
 
Example 17
Source File: DownloadRunnable.java    From FileDownloader with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    FileDownloadConnection connection = null;
    final long beginOffset = connectTask.getProfile().currentOffset;
    boolean isConnected = false;
    do {

        try {
            if (paused) {
                return;
            }

            isConnected = false;
            connection = connectTask.connect();
            final int code = connection.getResponseCode();

            if (FileDownloadLog.NEED_LOG) {
                FileDownloadLog
                        .d(this, "the connection[%d] for %d, is connected %s with code[%d]",
                                connectionIndex, downloadId, connectTask.getProfile(), code);
            }

            if (code != HttpURLConnection.HTTP_PARTIAL && code != HttpURLConnection.HTTP_OK) {
                throw new SocketException(FileDownloadUtils.
                        formatString(
                                "Connection failed with request[%s] response[%s] "
                                        + "http-state[%d] on task[%d-%d], which is changed"
                                        + " after verify connection, so please try again.",
                                connectTask.getRequestHeader(),
                                connection.getResponseHeaderFields(),
                                code, downloadId, connectionIndex));
            }

            isConnected = true;
            final FetchDataTask.Builder builder = new FetchDataTask.Builder();

            if (paused) return;
            fetchDataTask = builder
                    .setDownloadId(downloadId)
                    .setConnectionIndex(connectionIndex)
                    .setCallback(callback)
                    .setHost(this)
                    .setWifiRequired(isWifiRequired)
                    .setConnection(connection)
                    .setConnectionProfile(this.connectTask.getProfile())
                    .setPath(path)
                    .build();

            fetchDataTask.run();

            if (paused) fetchDataTask.pause();
            break;

        } catch (IllegalAccessException | IOException | FileDownloadGiveUpRetryException
                | IllegalArgumentException e) {
            if (callback.isRetry(e)) {
                if (isConnected && fetchDataTask == null) {
                    // connected but create fetch data task failed, give up directly.
                    FileDownloadLog.w(this, "it is valid to retry and connection is valid but"
                            + " create fetch-data-task failed, so give up directly with %s", e);
                    callback.onError(e);
                    break;
                } else {
                    if (fetchDataTask != null) {
                        //update currentOffset in ConnectionProfile
                        final long downloadedOffset = getDownloadedOffset();
                        if (downloadedOffset > 0) {
                            connectTask.updateConnectionProfile(downloadedOffset);
                        }
                    }
                    callback.onRetry(e);
                }
            } else {
                callback.onError(e);
                break;
            }

        } finally {
            if (connection != null) connection.ending();
        }
    } while (true);

}
 
Example 18
Source File: SampleGenerator.java    From chromadoze with GNU General Public License v3.0 4 votes vote down vote up
private void threadLoop() throws StopException {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    // Chunk-making progress:
    final SampleGeneratorState state = new SampleGeneratorState();
    SpectrumData spectrum = null;
    long waitMs = -1;

    while (true) {
        // This does one of 3 things:
        // - Throw StopException if stopThread() was called.
        // - Check if a new spectrum is waiting.
        // - Block if there's no work to do.
        final SpectrumData newSpectrum = popPendingSpectrum(waitMs);
        if (newSpectrum != null && !newSpectrum.sameSpectrum(spectrum)) {
            spectrum = newSpectrum;
            state.reset();
            mNoiseService.updatePercentAsync(state.getPercent());
        } else if (waitMs == -1) {
            // Nothing changed.  Keep waiting.
            continue;
        }

        final long startMs = SystemClock.elapsedRealtime();

        // Generate the next chunk of sound.
        float[] dctData = doIDCT(state.getChunkSize(), spectrum);
        if (mSampleShuffler.handleChunk(dctData, state.getStage())) {
            // Not dropped.
            state.advance();
            mNoiseService.updatePercentAsync(state.getPercent());
        }

        // Avoid burning the CPU while the user is scrubbing.  For the
        // first couple large chunks, the next chunk should be ready
        // when this one is ~75% finished playing.
        final long sleepTargetMs = state.getSleepTargetMs(mParams.SAMPLE_RATE);
        final long elapsedMs = SystemClock.elapsedRealtime() - startMs;
        waitMs = sleepTargetMs - elapsedMs;
        if (waitMs < 0) waitMs = 0;
        if (waitMs > sleepTargetMs) waitMs = sleepTargetMs;

        if (state.done()) {
            // No chunks left; save RAM.
            mDct = null;
            mLastDctSize = -1;
            waitMs = -1;
        }
    }
}
 
Example 19
Source File: AppExecutorsModule.java    From white-label-event-app with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
    Process.setThreadPriority(prio);
    super.run();
    runnable.run();
}
 
Example 20
Source File: DefaultLithoHandlerDynamicPriority.java    From litho with Apache License 2.0 4 votes vote down vote up
public void setThreadPriority(int priority) {
  Process.setThreadPriority(mHandlerThread.getThreadId(), priority);
}