Abh*_*ain 6 multithreading android executor android-context
在API级别28(Pie)上,Context该类中引入了一种新方法来获取主线程的Executor getMainExecutor()。
如何使该执行程序的API级别低于28?
ant*_*i93 21
您可以使用(例如在活动中):
ContextCompat.getMainExecutor(this);
Run Code Online (Sandbox Code Playgroud)
您可以使用来自改造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)
您可以使用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)
| 归档时间: |
|
| 查看次数: |
1426 次 |
| 最近记录: |