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 import java.util.concurrent.Future; 24 25 public class ThreadUtils { 26 27 private static volatile Thread sMainThread; 28 private static volatile Handler sMainThreadHandler; 29 private static volatile ExecutorService sSingleThreadExecutor; 30 31 /** 32 * Returns true if the current thread is the UI thread. 33 */ isMainThread()34 public static boolean isMainThread() { 35 if (sMainThread == null) { 36 sMainThread = Looper.getMainLooper().getThread(); 37 } 38 return Thread.currentThread() == sMainThread; 39 } 40 41 /** 42 * Returns a shared UI thread handler. 43 */ getUiThreadHandler()44 public static Handler getUiThreadHandler() { 45 if (sMainThreadHandler == null) { 46 sMainThreadHandler = new Handler(Looper.getMainLooper()); 47 } 48 49 return sMainThreadHandler; 50 } 51 52 /** 53 * Checks that the current thread is the UI thread. Otherwise throws an exception. 54 */ ensureMainThread()55 public static void ensureMainThread() { 56 if (!isMainThread()) { 57 throw new RuntimeException("Must be called on the UI thread"); 58 } 59 } 60 61 /** 62 * Posts runnable in background using shared background thread pool. 63 * 64 * @Return A future of the task that can be monitored for updates or cancelled. 65 */ postOnBackgroundThread(Runnable runnable)66 public static Future postOnBackgroundThread(Runnable runnable) { 67 if (sSingleThreadExecutor == null) { 68 sSingleThreadExecutor = Executors.newSingleThreadExecutor(); 69 } 70 return sSingleThreadExecutor.submit(runnable); 71 } 72 73 /** 74 * Posts the runnable on the main thread. 75 */ postOnMainThread(Runnable runnable)76 public static void postOnMainThread(Runnable runnable) { 77 getUiThreadHandler().post(runnable); 78 } 79 80 } 81