blob: 88adcdb16edcb27acb99c10b9399f7270fc34d26 [file] [log] [blame]
Juan Lang5efe8f02017-05-04 16:59:46 -07001/*
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 */
16package com.android.settingslib.utils;
17
Fan Zhangd30c05c2017-07-21 16:59:57 -070018import android.os.Handler;
Juan Lang5efe8f02017-05-04 16:59:46 -070019import android.os.Looper;
20
Fan Zhangdadfd502017-07-26 11:00:51 -070021import java.util.concurrent.ExecutorService;
22import java.util.concurrent.Executors;
23
Juan Lang5efe8f02017-05-04 16:59:46 -070024public class ThreadUtils {
Fan Zhangd30c05c2017-07-21 16:59:57 -070025
Juan Lang5efe8f02017-05-04 16:59:46 -070026 private static volatile Thread sMainThread;
Fan Zhangd30c05c2017-07-21 16:59:57 -070027 private static volatile Handler sMainThreadHandler;
Fan Zhangdadfd502017-07-26 11:00:51 -070028 private static volatile ExecutorService sSingleThreadExecutor;
Juan Lang5efe8f02017-05-04 16:59:46 -070029
30 /**
31 * Returns true if the current thread is the UI thread.
32 */
33 public static boolean isMainThread() {
34 if (sMainThread == null) {
35 sMainThread = Looper.getMainLooper().getThread();
36 }
37 return Thread.currentThread() == sMainThread;
38 }
39
40 /**
Fan Zhangd30c05c2017-07-21 16:59:57 -070041 * Returns a shared UI thread handler.
42 */
43 public static Handler getUiThreadHandler() {
44 if (sMainThreadHandler == null) {
45 sMainThreadHandler = new Handler(Looper.getMainLooper());
46 }
47
48 return sMainThreadHandler;
49 }
50
51 /**
Juan Lang5efe8f02017-05-04 16:59:46 -070052 * Checks that the current thread is the UI thread. Otherwise throws an exception.
53 */
54 public static void ensureMainThread() {
55 if (!isMainThread()) {
56 throw new RuntimeException("Must be called on the UI thread");
57 }
58 }
59
Fan Zhangd30c05c2017-07-21 16:59:57 -070060 /**
Fan Zhangdadfd502017-07-26 11:00:51 -070061 * Posts runnable in background using shared background thread pool.
62 */
63 public static void postOnBackgroundThread(Runnable runnable) {
64 if (sSingleThreadExecutor == null) {
65 sSingleThreadExecutor = Executors.newSingleThreadExecutor();
66 }
67 sSingleThreadExecutor.execute(runnable);
68 }
69
70 /**
Fan Zhangd30c05c2017-07-21 16:59:57 -070071 * Posts the runnable on the main thread.
72 */
73 public static void postOnMainThread(Runnable runnable) {
74 getUiThreadHandler().post(runnable);
75 }
76
Juan Lang5efe8f02017-05-04 16:59:46 -070077}