Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 574f0413 authored by TreeHugger Robot's avatar TreeHugger Robot Committed by Android (Google) Code Review
Browse files

Merge "Make a helper method to post work to ui thread."

parents 44e1751c d30c05c2
Loading
Loading
Loading
Loading
+21 −0
Original line number Diff line number Diff line
@@ -15,10 +15,13 @@
 */
package com.android.settingslib.utils;

import android.os.Handler;
import android.os.Looper;

public class ThreadUtils {

    private static volatile Thread sMainThread;
    private static volatile Handler sMainThreadHandler;

    /**
     * Returns true if the current thread is the UI thread.
@@ -30,6 +33,17 @@ public class ThreadUtils {
        return Thread.currentThread() == sMainThread;
    }

    /**
     * Returns a shared UI thread handler.
     */
    public static Handler getUiThreadHandler() {
        if (sMainThreadHandler == null) {
            sMainThreadHandler = new Handler(Looper.getMainLooper());
        }

        return sMainThreadHandler;
    }

    /**
     * Checks that the current thread is the UI thread. Otherwise throws an exception.
     */
@@ -39,4 +53,11 @@ public class ThreadUtils {
        }
    }

    /**
     * Posts the runnable on the main thread.
     */
    public static void postOnMainThread(Runnable runnable) {
        getUiThreadHandler().post(runnable);
    }

}
+28 −3
Original line number Diff line number Diff line
@@ -16,14 +16,16 @@
package com.android.settingslib.utils;


import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;

import com.android.settingslib.TestConfig;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import org.robolectric.shadows.ShadowLooper;

@RunWith(RobolectricTestRunner.class)
@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
@@ -56,4 +58,27 @@ public class ThreadUtilsTest {
        background.start();
        background.join();
    }

    @Test
    public void testPostOnMainThread_shouldRunOnMainTread() throws Exception {
        TestRunnable cr = new TestRunnable();
        ShadowLooper.pauseMainLooper();
        ThreadUtils.postOnMainThread(cr);
        assertThat(cr.called).isFalse();

        ShadowLooper.runUiThreadTasks();
        assertThat(cr.called).isTrue();
        assertThat(cr.onUiThread).isTrue();
    }

    private static class TestRunnable implements Runnable {
        volatile boolean called;
        volatile boolean onUiThread;

        public void run() {
            this.called = true;
            this.onUiThread = ThreadUtils.isMainThread();
        }
    }

}