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

自闭症网瘾萝莉.ら 提交于 2020-12-29 05:31:05

问题


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?


回答1:


You can use (in activity for example):

ContextCompat.getMainExecutor(this);

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




回答2:


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);
    }
}   



回答3:


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)
    }
}


来源:https://stackoverflow.com/questions/52642246/how-to-get-executor-for-main-thread-on-api-level-28

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!