1 /* 2 * Copyright (C) 2020 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 17 package com.android.documentsui; 18 19 import android.os.Looper; 20 21 /** Class for handler/thread utils. */ 22 public final class ThreadHelper { ThreadHelper()23 private ThreadHelper() { 24 } 25 26 static final String MUST_NOT_ON_MAIN_THREAD_MSG = 27 "This method should not be called on main thread."; 28 static final String MUST_ON_MAIN_THREAD_MSG = 29 "This method should only be called on main thread."; 30 31 /** Verifies that current thread is not the UI thread. */ assertNotOnMainThread()32 public static void assertNotOnMainThread() { 33 if (Looper.getMainLooper().getThread() == Thread.currentThread()) { 34 fatalAssert(MUST_NOT_ON_MAIN_THREAD_MSG); 35 } 36 } 37 38 /** Verifies that current thread is the UI thread. */ assertOnMainThread()39 public static void assertOnMainThread() { 40 if (Looper.getMainLooper().getThread() != Thread.currentThread()) { 41 fatalAssert(MUST_ON_MAIN_THREAD_MSG); 42 } 43 } 44 45 /** 46 * Exceptions thrown in background threads are silently swallowed on Android. Use the 47 * uncaught exception handler of the UI thread to force the app to crash. 48 */ fatalAssert(final String message)49 public static void fatalAssert(final String message) { 50 crashMainThread(new AssertionError(message)); 51 } 52 crashMainThread(Throwable t)53 private static void crashMainThread(Throwable t) { 54 Thread.UncaughtExceptionHandler uiThreadExceptionHandler = 55 Looper.getMainLooper().getThread().getUncaughtExceptionHandler(); 56 uiThreadExceptionHandler.uncaughtException(Thread.currentThread(), t); 57 } 58 } 59