1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.android.settingslib.utils;
17 
18 import android.os.Handler;
19 import android.os.Looper;
20 
21 import java.util.concurrent.ExecutorService;
22 import java.util.concurrent.Executors;
23 
24 public class ThreadUtils {
25 
26     private static volatile Thread sMainThread;
27     private static volatile Handler sMainThreadHandler;
28     private static volatile ExecutorService sSingleThreadExecutor;
29 
30     /**
31      * Returns true if the current thread is the UI thread.
32      */
isMainThread()33     public static boolean isMainThread() {
34         if (sMainThread == null) {
35             sMainThread = Looper.getMainLooper().getThread();
36         }
37         return Thread.currentThread() == sMainThread;
38     }
39 
40     /**
41      * Returns a shared UI thread handler.
42      */
getUiThreadHandler()43     public static Handler getUiThreadHandler() {
44         if (sMainThreadHandler == null) {
45             sMainThreadHandler = new Handler(Looper.getMainLooper());
46         }
47 
48         return sMainThreadHandler;
49     }
50 
51     /**
52      * Checks that the current thread is the UI thread. Otherwise throws an exception.
53      */
ensureMainThread()54     public static void ensureMainThread() {
55         if (!isMainThread()) {
56             throw new RuntimeException("Must be called on the UI thread");
57         }
58     }
59 
60     /**
61      * Posts runnable in background using shared background thread pool.
62      */
postOnBackgroundThread(Runnable runnable)63     public static void postOnBackgroundThread(Runnable runnable) {
64         if (sSingleThreadExecutor == null) {
65             sSingleThreadExecutor = Executors.newSingleThreadExecutor();
66         }
67         sSingleThreadExecutor.execute(runnable);
68     }
69 
70     /**
71      * Posts the runnable on the main thread.
72      */
postOnMainThread(Runnable runnable)73     public static void postOnMainThread(Runnable runnable) {
74         getUiThreadHandler().post(runnable);
75     }
76 
77 }
78