/** * Try to raise the priority of {@param threadId} to {@param targetThreadPriority}. * * @return the original thread priority of the target thread. */ public static int tryRaiseThreadPriority(int threadId, int targetThreadPriority) { // Main thread is about to be blocked, raise the running thread priority. final int originalThreadPriority = Process.getThreadPriority(threadId); boolean success = false; while (!success && targetThreadPriority < originalThreadPriority) { // Keep trying to increase thread priority of running thread as long as it is an increase. try { Process.setThreadPriority(threadId, targetThreadPriority); success = true; } catch (SecurityException e) { /* From {@link Process#THREAD_PRIORITY_DISPLAY}, some applications can not change the thread priority to that of the main thread. This catches that potential error and tries to set a lower priority. */ targetThreadPriority += Process.THREAD_PRIORITY_LESS_FAVORABLE; } } return originalThreadPriority; } }
/** * Try to raise the priority of {@param threadId} to the priority of the calling thread * * @return the original thread priority of the target thread. */ public static int tryInheritThreadPriorityFromCurrentThread(int threadId) { return tryRaiseThreadPriority(threadId, Process.getThreadPriority(Process.myTid())); }
@Test public void getThreadPriority_notSet_returnsZero() { assertThat(android.os.Process.getThreadPriority(123)).isEqualTo(0); }
@Test public void getThreadPriority_returnsThreadPriority() { android.os.Process.setThreadPriority(123, android.os.Process.THREAD_PRIORITY_VIDEO); assertThat(android.os.Process.getThreadPriority(123)) .isEqualTo(android.os.Process.THREAD_PRIORITY_VIDEO); }
@Test public void getThreadPriority_currentThread_returnsCurrentThreadPriority() { android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO); assertThat(android.os.Process.getThreadPriority(/*tid=*/ 0)) .isEqualTo(android.os.Process.THREAD_PRIORITY_AUDIO); }
@Test public void setThreadPriorityOneArgument_setsCurrentThreadPriority() { android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO); assertThat(android.os.Process.getThreadPriority(android.os.Process.myTid())) .isEqualTo(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO); } }