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

Abh*_*ain 6 multithreading android executor android-context

在API级别28(Pie)上,Context该类中引入了一种新方法来获取主线程的Executor getMainExecutor()

如何使该执行程序的API级别低于28?

ata*_*nko 8

您可以使用来自改造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);
    }
}   
Run Code Online (Sandbox Code Playgroud)


Cés*_*eña 5

您可以使用new HandlerExecutor(Looper.getMainLooper());com.google.android.gms.common.util.concurrent.HandlerExecutor...到底是相同的答案atarasenko

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

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