cn.keayuan.util.Platform Maven / Gradle / Ivy
The newest version!
package cn.keayuan.util;
import java.util.concurrent.Executor;
import cn.keayuan.util.log.ILog;
import cn.keayuan.util.log.Logger;
/**
* Created by keayuan on 2019-12-02.
*
* @author keayuan
*/
public final class Platform {
private static ILog log;
private static final IPlatform PLATFORM;
public static final boolean isAndroid;
static {
boolean is = false;
try {
if (Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null) > 0) {
is = true;
}
} catch (ClassNotFoundException | IllegalAccessException | NoSuchFieldException ignored) {
}
isAndroid = is;
PLATFORM = isAndroid ? new PlatformAndroid() : new IPlatform();
}
Platform() {}
public static void setLogger(ILog iLog) {
log = iLog;
}
public static ILog logger() {
return log == null ? Logger.getLog() : log;
}
public static void runIO(Runnable run) {
PLATFORM.runIO(run);
}
public static void runMain(Runnable run) {
PLATFORM.runMain(run);
}
public static boolean isMainThread() {
return PLATFORM.isMainThread();
}
public static Executor getMainExecutor() {
return PLATFORM.getMainExecutor();
}
private static class IPlatform {
void runIO(Runnable run) {ThreadUtils.getIOPool().execute(run);}
void runMain(Runnable run) {getMainExecutor().execute(run);}
boolean isMainThread() {return true;}
Executor getMainExecutor() {return ThreadUtils.getCPUPool();}
}
private static class PlatformAndroid extends Platform.IPlatform {
private final android.os.Handler mainHandler;
private final Executor mainExecutor = new Executor() {
@Override
public void execute(Runnable command) {
mainHandler.post(command);
}
};
PlatformAndroid() {
mainHandler = new android.os.Handler(android.os.Looper.getMainLooper());
}
@Override
void runMain(Runnable runnable) {mainHandler.post(runnable);}
@Override
boolean isMainThread() {return android.os.Looper.getMainLooper() == android.os.Looper.myLooper();}
@Override
Executor getMainExecutor() {return mainExecutor;}
}
}