如何在 API 级别 < 28 上获取主线程的执行器

How to get Executor for main thread on API level < 28

在 API 级别 28(Pie) Context class 中引入了一种新方法来获取主线程的执行器 getMainExecutor().

如何让这个执行者的 API 等级低于 28?

您可以使用改造中的代码片段 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);
    }
}   

您可以使用 com.google.android.gms.common.util.concurrent.HandlerExecutor 中的 new HandlerExecutor(Looper.getMainLooper());...最终它的答案与 atarasenko 相同。

我为此在 Kotlin 中添加了一个扩展:

fun Context.mainExecutor(): Executor {
    return if (VERSION.SDK_INT >= VERSION_CODES.P) {
        mainExecutor
    } else {
        HandlerExecutor(mainLooper)
    }
}

您可以使用(例如 activity):

ContextCompat.getMainExecutor(this);

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