23

On API level 28(Pie) a new method is introduced in the Context class to get Executor for the main thread getMainExecutor().

How to get this executor on API level below 28?

Abhishek Jain
  • 3,562
  • 2
  • 26
  • 44

3 Answers3

46

You can use (in activity for example):

ContextCompat.getMainExecutor(this);

https://developer.android.com/reference/androidx/core/content/ContextCompat.html#getMainExecutor(android.content.Context)

antaki93
  • 704
  • 7
  • 10
12

You can use code snippet from retrofit https://github.com/square/retrofit/blob/master/retrofit/src/main/java/retrofit2/Platform.java

public class MainThreadExecutor implements Executor {
    private final Handler handler = new Handler(Looper.getMainLooper());

    @Override 
    public void execute(Runnable r) {
        handler.post(r);
    }
}   
atarasenko
  • 1,768
  • 14
  • 19
  • d= (◕‿↼ ) Right! there was a reason why `Executor` is just an interface, **allowing it's implements (instead of searching all over for it in different API).** – Top-Master May 29 '22 at 17:42
8

You can use new HandlerExecutor(Looper.getMainLooper()); from com.google.android.gms.common.util.concurrent.HandlerExecutor...in the end it's the same answer as atarasenko.

I added an extension in Kotlin for that:

fun Context.mainExecutor(): Executor {
    return if (VERSION.SDK_INT >= VERSION_CODES.P) {
        mainExecutor
    } else {
        HandlerExecutor(mainLooper)
    }
}
César N.
  • 449
  • 4
  • 7