Skip to content

Instantly share code, notes, and snippets.

@BCsl
Last active June 29, 2025 08:32
Show Gist options
  • Select an option

  • Save BCsl/dd30f8df6fe76b346b12295451aefbf6 to your computer and use it in GitHub Desktop.

Select an option

Save BCsl/dd30f8df6fe76b346b12295451aefbf6 to your computer and use it in GitHub Desktop.
NTP 网络时间
/**
* Created by chensuilun on 2017/7/4.
*/
public class NTUSUtils {
private static final String TAG = "NTUSUtils";
private static final String NTP_TRUSTED_TIME = "android.util.NtpTrustedTime";
private static final String GET_INSTANCE = "getInstance";//private NtpTrustedTime getInstance(Context context)
private static final String FORCE_REFRESH = "forceRefresh"; //public boolean forceRefresh()
private static final String GET_CACHED_NTP_TIME = "getCachedNtpTime";//public long getCachedNtpTime()
private static Context sContext = AppApplication.getContext();
private static Method sGetNtpTimeMethod;
private static Method sForceRefreshMethod;
private static Class sNTPTrustedTimeClz;
private static Object sNtpTrustedTimeInstance;
static {
try {
sNTPTrustedTimeClz = Class.forName(NTP_TRUSTED_TIME);
Method instanceMethod = sNTPTrustedTimeClz.getDeclaredMethod(GET_INSTANCE, Context.class);
instanceMethod.setAccessible(true);
sNtpTrustedTimeInstance = instanceMethod.invoke(null, sContext);
sGetNtpTimeMethod = sNTPTrustedTimeClz.getDeclaredMethod(GET_CACHED_NTP_TIME);
sForceRefreshMethod = sNTPTrustedTimeClz.getDeclaredMethod(FORCE_REFRESH);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
@WorkerThread
public static boolean forceFresh() {
if (BuildConfig.DEBUG) {
Log.d(TAG, "forceFresh() called with: " + "");
}
if (sForceRefreshMethod != null) {
try {
return (boolean) sForceRefreshMethod.invoke(sNtpTrustedTimeInstance);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
return false;
}
public static long getCachedNtpTime() {
if (BuildConfig.DEBUG) {
Log.d(TAG, "getCachedNtpTime() called with: " + "");
}
if (sGetNtpTimeMethod != null) {
try {
return (long) sGetNtpTimeMethod.invoke(sNtpTrustedTimeInstance);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
return -1;
}
}
@asdfcjf

asdfcjf commented Jun 20, 2018

Copy link
Copy Markdown

是调用forceFresh这个方法么 我调用了 没作用

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment