summaryrefslogtreecommitdiff
path: root/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/utils/ThreadUtils.java
blob: 6c4018622cf69cb5d08aba142a8c02cf1f9ef756 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.mapbox.mapboxsdk.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.os.Looper;
import android.support.annotation.NonNull;
import com.mapbox.mapboxsdk.exceptions.CalledFromWorkerThreadException;

/**
 * Utility class to verify if execution is running on the main thread.
 * <p>
 * Verification only runs for debug builds.
 * </p>
 */
public class ThreadUtils {

  private static Boolean debug;

  /**
   * Initialises the thread utils, verifies debug state of the consuming app.
   *
   * @param context Context hosting the Mapbox Maps SDK for Android
   * @return this
   */
  public static ThreadUtils init(@NonNull Context context) {
    debug = (0 != (context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE));
    return null;
  }

  /**
   * Validates if execution is running on the main thread.
   *
   * @param origin  the origin of the execution
   */
  public static void checkThread(@NonNull String origin) {
    if (debug == null) {
      throw new IllegalStateException("ThreadUtils isn't correctly initialised");
    }

    if (debug) {
      if (Looper.myLooper() != Looper.getMainLooper()) {
        throw new CalledFromWorkerThreadException(
          String.format("%s interactions should happen on the UI thread.", origin)
        );
      }
    }
  }
}